jma*_*mac 3 java postgresql jdbc
我正在尝试从新创建的表中获取列列表(它是在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()));
}
}
Run Code Online (Sandbox Code Playgroud)
和输出:
Found 0 cols.
Autocommit is set to true.
Run Code Online (Sandbox Code Playgroud)
问题出在你的tablename的情况下:
String tableName = "Table_"
Run Code Online (Sandbox Code Playgroud)
因为这是一个不带引号的标识符(一件好事),当Postgres将其名称存储在系统目录中时,名称将转换为小写.
DatabaseMetaData API调用区分大小写("Table_"!= "table_"),因此您需要传递小写的表名:
ResultSet rs = metaData.getColumns(null, null, tableName.toLowerCase(), null))
Run Code Online (Sandbox Code Playgroud)
有关标识符使用方式的更多详细信息,请参见手册:http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS