如何从 JDBC 检索序列元数据?

发布于 2024-10-31 23:32:08 字数 727 浏览 1 评论 0 原文

我正在尝试从 Java 代码(使用基本 JDBC)检索 Oracle DB 的不同类型的元数据。例如,如果我想检索带有 _FOO 后缀的表列表,我可以执行以下操作:

Connection connection = dataSource.getConnection();
DatabaseMetaData meta = connection.getMetaData();
ResultSet tables = meta.getTables(connection.getCatalog(), null, "%_FOO", new String[] { "TABLE" });
// Iterate on the ResultSet to get information on tables...

现在,我想从数据库中检索所有序列(例如例如所有名为 S_xxx_FOO 的序列)。

我该怎么做,因为我在 DatabaseMetaData 与序列相关?

我是否必须运行 select * from user_sequences 这样的查询?

I am trying to retrieve different kind of metadata of my Oracle DB from Java code (using basic JDBC). For example, if I want to retrieve the list of tables with _FOO suffix, I can do something like:

Connection connection = dataSource.getConnection();
DatabaseMetaData meta = connection.getMetaData();
ResultSet tables = meta.getTables(connection.getCatalog(), null, "%_FOO", new String[] { "TABLE" });
// Iterate on the ResultSet to get information on tables...

Now, I want to retrieve all the sequences from my database (for example all sequence named S_xxx_FOO).

How would I do that, as I don't see anything in DatabaseMetaData related to sequences?

Do I have to run a query like select * from user_sequences ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

幽梦紫曦~ 2024-11-07 23:32:08

有同样的问题。这相当容易。只需将“SEQUENCE”传递到 getMetaData().getTables() 类型参数中即可。

在您的具体情况下,它会是这样的:

meta.getTables(connection.getCatalog(), null, "%_FOO", new String[] { "SEQUENCE" });

Had the same question. It's fairly easy. Just pass in "SEQUENCE" into the getMetaData().getTables() types param.

In your specific case it would be something like:

meta.getTables(connection.getCatalog(), null, "%_FOO", new String[] { "SEQUENCE" });
℉絮湮 2024-11-07 23:32:08

您无法通过 JDBC API 执行此操作,因为某些数据库(仍然)不支持序列。

获取它们的唯一方法是查询 DBMS 的系统目录(我猜您提到的 user_sequences 是 Oracle)

You can't do this through the JDBC API, because some databases (still) do not support sequences.

The only way to get them is to query the system catalog of your DBMS (I guess it's Oracle in your case as you mention user_sequences)

苍景流年 2024-11-07 23:32:08

鉴于最新版本的 Oracle JDBC 驱动程序(例如 12.1.0.2)不返回序列信息< /a> 当您调用 DatabaseMetaData#g​​etTables,其中 types 设置为 ["SEQUENCE"],最好的办法是自己运行必要的查询,例如:

  SELECT o.owner AS sequence_owner,
       o.object_name AS sequence_name
  FROM all_objects o
  WHERE o.owner LIKE 'someOwnerPattern' ESCAPE '/'
    AND o.object_name LIKE 'someNamePattern' ESCAPE '/'
    AND o.object_type = 'SEQUENCE'
  ORDER BY 1, 2

... 其中 someOwnerPatternsomeNamePattern 是 SQL 模式,例如与LIKE 运算符一起使用的那些(例如% 匹配任何内容)。

这与驱动程序本身运行的查询基本相同,只是它查询 SEQUENCE 类型的对象。

Given that recent versions of the Oracle JDBC drivers (e.g. 12.1.0.2) don't return sequence information when you call DatabaseMetaData#getTables with types set to ["SEQUENCE"], your best bet is to run the necessary query yourself, e.g.:

  SELECT o.owner AS sequence_owner,
       o.object_name AS sequence_name
  FROM all_objects o
  WHERE o.owner LIKE 'someOwnerPattern' ESCAPE '/'
    AND o.object_name LIKE 'someNamePattern' ESCAPE '/'
    AND o.object_type = 'SEQUENCE'
  ORDER BY 1, 2

... where someOwnerPattern and someNamePattern are SQL patterns like the ones you'd use with the LIKE operator (e.g. % matches anything).

This is basically the same as the query run by the driver itself, except that it queries for objects of type SEQUENCE.

陌伤浅笑 2024-11-07 23:32:08

您可以使用 hibernate dialect api 来检索序列名称。请参阅:http://docs.jboss.org /hibernate/orm/3.2/api/org/hibernate/dialect/Dialect.html

从下面的示例中,您可以看到如何使用方言来获取序列名称

public static void main(String[] args) {
        Connection jdbcConnection = null;
        try {
            jdbcConnection = DriverManager.getConnection("", "", "");
            printAllSequenceName(jdbcConnection);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if(jdbcConnection != null) {
                try {
                    jdbcConnection.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
}

public static void printAllSequenceName(Connection conn) throws JDBCConnectionException, SQLException {
        DialectResolver dialectResolver = new StandardDialectResolver();
        Dialect dialect =  dialectResolver.resolveDialect(conn.getMetaData());

        if ( dialect.supportsSequences() ) {
            String sql = dialect.getQuerySequencesString();
            if (sql!=null) {

                Statement statement = null;
                ResultSet rs = null;
                try {
                    statement = conn.createStatement();
                    rs = statement.executeQuery(sql);

                    while ( rs.next() ) {
                        System.out.println("Sequence Name : " +  rs.getString(1));
                    }
                }
                finally {
                    if (rs!=null) rs.close();
                    if (statement!=null) statement.close();
                }

            }
        }
    }

如果您不想使用 hibernate,那么您可以创建自定义顺序特定实现。

自定义实现的示例代码

interface SequenceQueryGenerator {
    String getSelectSequenceNextValString(String sequenceName);
    String getCreateSequenceString(String sequenceName, int initialValue, int incrementSize); 
    String getDropSequenceStrings(String sequenceName); 
    String getQuerySequencesString(); 
}


class OracleSequenceQueryGenerator implements SequenceQueryGenerator {

    @Override
    public String getSelectSequenceNextValString(String sequenceName) {
        return "select " + getSelectSequenceNextValString( sequenceName ) + " from dual";
    }

    @Override
    public String getCreateSequenceString(String sequenceName,
            int initialValue, int incrementSize) {
        return "create sequence " + sequenceName +  " start with " + initialValue + " increment by " + incrementSize;
    }

    @Override
    public String getDropSequenceStrings(String sequenceName) {
        return "drop sequence " + sequenceName;
    }

    @Override
    public String getQuerySequencesString() {
        return "select sequence_name from user_sequences";
    }

}


class PostgresSequenceQueryGenerator implements SequenceQueryGenerator {

    @Override
    public String getSelectSequenceNextValString(String sequenceName) {
        return "select " + getSelectSequenceNextValString( sequenceName );
    }

    @Override
    public String getCreateSequenceString(String sequenceName,
            int initialValue, int incrementSize) {
        return "create sequence " + sequenceName + " start " + initialValue + " increment " + incrementSize;
    }

    @Override
    public String getDropSequenceStrings(String sequenceName) {
        return "drop sequence " + sequenceName;
    }

    @Override
    public String getQuerySequencesString() {
        return "select relname from pg_class where relkind='S'";
    }

}

public void printSequenceName (SequenceQueryGenerator queryGenerator, Connection conn) throws SQLException {
        String sql = queryGenerator.getQuerySequencesString();
        if (sql!=null) {

            Statement statement = null;
            ResultSet rs = null;
            try {
                statement = conn.createStatement();
                rs = statement.executeQuery(sql);

                while ( rs.next() ) {
                    System.out.println("Sequence Name : " +  rs.getString(1));
                }
            }
            finally {
                if (rs!=null) rs.close();
                if (statement!=null) statement.close();
            }

        }
    }

public static void main(String[] args) {
        Connection jdbcConnection = null;
        try {
            jdbcConnection = DriverManager.getConnection("", "", "");
            printAllSequenceName(new OracleSequenceQueryGenerator(), jdbcConnection);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if(jdbcConnection != null) {
                try {
                    jdbcConnection.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
}

You can use the hibernate dialect api for retrieving sequence Name. see : http://docs.jboss.org/hibernate/orm/3.2/api/org/hibernate/dialect/Dialect.html

From below example, you can see how to use dialect to get sequence names

public static void main(String[] args) {
        Connection jdbcConnection = null;
        try {
            jdbcConnection = DriverManager.getConnection("", "", "");
            printAllSequenceName(jdbcConnection);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if(jdbcConnection != null) {
                try {
                    jdbcConnection.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
}

public static void printAllSequenceName(Connection conn) throws JDBCConnectionException, SQLException {
        DialectResolver dialectResolver = new StandardDialectResolver();
        Dialect dialect =  dialectResolver.resolveDialect(conn.getMetaData());

        if ( dialect.supportsSequences() ) {
            String sql = dialect.getQuerySequencesString();
            if (sql!=null) {

                Statement statement = null;
                ResultSet rs = null;
                try {
                    statement = conn.createStatement();
                    rs = statement.executeQuery(sql);

                    while ( rs.next() ) {
                        System.out.println("Sequence Name : " +  rs.getString(1));
                    }
                }
                finally {
                    if (rs!=null) rs.close();
                    if (statement!=null) statement.close();
                }

            }
        }
    }

If you don't desire to use hibernate, then you have to crate custom sequential specific implementation.

Sample code for custom implementation

interface SequenceQueryGenerator {
    String getSelectSequenceNextValString(String sequenceName);
    String getCreateSequenceString(String sequenceName, int initialValue, int incrementSize); 
    String getDropSequenceStrings(String sequenceName); 
    String getQuerySequencesString(); 
}


class OracleSequenceQueryGenerator implements SequenceQueryGenerator {

    @Override
    public String getSelectSequenceNextValString(String sequenceName) {
        return "select " + getSelectSequenceNextValString( sequenceName ) + " from dual";
    }

    @Override
    public String getCreateSequenceString(String sequenceName,
            int initialValue, int incrementSize) {
        return "create sequence " + sequenceName +  " start with " + initialValue + " increment by " + incrementSize;
    }

    @Override
    public String getDropSequenceStrings(String sequenceName) {
        return "drop sequence " + sequenceName;
    }

    @Override
    public String getQuerySequencesString() {
        return "select sequence_name from user_sequences";
    }

}


class PostgresSequenceQueryGenerator implements SequenceQueryGenerator {

    @Override
    public String getSelectSequenceNextValString(String sequenceName) {
        return "select " + getSelectSequenceNextValString( sequenceName );
    }

    @Override
    public String getCreateSequenceString(String sequenceName,
            int initialValue, int incrementSize) {
        return "create sequence " + sequenceName + " start " + initialValue + " increment " + incrementSize;
    }

    @Override
    public String getDropSequenceStrings(String sequenceName) {
        return "drop sequence " + sequenceName;
    }

    @Override
    public String getQuerySequencesString() {
        return "select relname from pg_class where relkind='S'";
    }

}

public void printSequenceName (SequenceQueryGenerator queryGenerator, Connection conn) throws SQLException {
        String sql = queryGenerator.getQuerySequencesString();
        if (sql!=null) {

            Statement statement = null;
            ResultSet rs = null;
            try {
                statement = conn.createStatement();
                rs = statement.executeQuery(sql);

                while ( rs.next() ) {
                    System.out.println("Sequence Name : " +  rs.getString(1));
                }
            }
            finally {
                if (rs!=null) rs.close();
                if (statement!=null) statement.close();
            }

        }
    }

public static void main(String[] args) {
        Connection jdbcConnection = null;
        try {
            jdbcConnection = DriverManager.getConnection("", "", "");
            printAllSequenceName(new OracleSequenceQueryGenerator(), jdbcConnection);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if(jdbcConnection != null) {
                try {
                    jdbcConnection.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文