从jdbc / postgresql获取新创建表的列元数据

杰马克

我正在尝试从新创建的表中获取列列表(它是在Java代码中创建的)。问题是我没有得到专栏。该代码适用于数据库中已经存在的表,但是如果我创建一个新表并尝试立即获取列信息,它将找不到任何内容。

更新:这是我用于测试的完整代码:

@Test
public void testtest() throws Exception {
    try (Connection conn = dataSource.getConnection()) {
        String tableName = "Table_" + UUID.randomUUID().toString().replace("-", "");
        try (Statement statement = conn.createStatement()) {
            statement.executeUpdate(String.format("create table %s (id int primary key,name varchar(30));", tableName));
        }
        DatabaseMetaData metaData = conn.getMetaData();
        try (ResultSet rs = metaData.getColumns(null, null, tableName, null)) {
            int colsFound = 0;
            while (rs.next()) {
                colsFound++;
            }
            System.out.println(String.format("Found %s cols.", colsFound));
        }
        System.out.println(String.format("Autocommit is set to %s.", conn.getAutoCommit()));
    }
}

和输出:

Found 0 cols.
Autocommit is set to true.
a_horse_with_no_name

问题在于您的表名的情况:

String tableName = "Table_" 

因为这是一个未加引号的标识符(这是一件好事),所以当Postgres将其名称存储在系统目录中时,该名称将转换为小写。

DatabaseMetaData API调用区分大小写("Table_"!= "table_"),因此您需要传递小写的表名:

ResultSet rs = metaData.getColumns(null, null, tableName.toLowerCase(), null))

有关标识符如何使用的更多详细信息,请参见手册:http : //www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章