簡體   English   中英

從jdbc / postgresql獲取新創建的表的列元數據

[英]Getting column metadata from jdbc/postgresql for newly created table

我正在嘗試從新創建的表中獲取列列表(它是在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.

問題出在你的tablename的情況下:

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

我做了簡單的測試,似乎工作。 我可以使用PostgreSQL JDBC創建新表並顯示其列(我使用Jython):

conn = db.createStatement()
conn.execute("CREATE TABLE new_table (id SERIAL, txt VARCHAR(200))")
db_meta_data = db.getMetaData()
for tbl_name in ('date_test', 'new_table'):
    print('\n-- %s --' % (tbl_name))
    rs = db_meta_data.getColumns(None, None, tbl_name, None)
    while (rs.next()):
        print('%s:%s' % (rs.getString(3), rs.getString(4)))
conn.close()

此代碼顯示已存在的表的列: date_test和剛剛創建的new_table 我還添加了一些代碼來在CREATE TABLE之后關閉連接,但我的結果總是相同且正確的。

也許這是你的JDBC驅動程序的問題。 我使用postgresql-9.3-1100.jdbc41.jar驅動程序。

這可能也是用戶權限的問題。 您是否使用相同的用戶創建表和獲取元數據? psqlpgAdmin或其他工具中是否可以看到新表?

其他原因是PostgreSQL也使用事務進行模式更改。 因此,如果禁用默認自動提交和關閉連接,則架構更改將丟失。 你使用db.setAutoCommit(false)嗎?

您還可以直接查詢PostgreSQL架構:

SELECT DISTINCT table_name, column_name
FROM information_schema.columns
WHERE table_schema='public'
AND table_name = 'new_table'
ORDER BY 1, 2 

奇怪地給小寫傳遞表名稱為getColumns方法確實有效...感謝查詢MichałNiklas讓我走上了正確的軌道。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM