Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting column metadata from jdbc/postgresql for newly created table

I'm trying to get the column list from newly created table(it is created in the java code). The thing is that I do not get the columns. The code works for tables that are already in the database, but if i create a new one and try to get the column info immediately it does not find any...

Update: Here is full code that I used for testing:

@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()));
    }
}

The and the output:

Found 0 cols.
Autocommit is set to true.
like image 893
jmac Avatar asked Feb 14 '23 14:02

jmac


1 Answers

The problem is with the case of your tablename:

String tableName = "Table_" 

As that is an unquoted identifier (a good thing) the name is converted to lowercase when Postgres stores its name in the system catalog.

The DatabaseMetaData API calls are case sensitive ( "Table_" != "table_"), so you need to pass the lowercase tablename:

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

More details on how identifiers are using are in the manual: http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS

like image 154
a_horse_with_no_name Avatar answered Feb 16 '23 04:02

a_horse_with_no_name