-1

Given the name of a table, how to know the names of the columns using JDBC? I know it's something using DatabaseMetaData, examples are welcome!

Completing question:

I'm using HSQLDB and creating the table when I start the server and it seems that databasemetada is failing to read the column names.

String tableName = "cities";
DatabaseMetaData metaData = connection.getMetaData();
ResultSet resultSet = metaData.getColumns(null, null, tableName, null);
while(resultSet.next()){
System.out.println(resultSet.getString("COLUMN_NAME"));
}

The object resultSet.next() is coming empty.

Luciano Borges
  • 817
  • 3
  • 12
  • 31

3 Answers3

2

You can try upper case table name:

String tableName = "CITIES";
Jarandinor
  • 1,846
  • 15
  • 8
  • 1
    The reason this might work is that you need to use the tablename pattern as it is stored in the database, eg for case insensitive column names that are stored uppercase, you need to request them uppercased. The [javadoc says](http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html#getColumns(java.lang.String,%20java.lang.String,%20java.lang.String,%20java.lang.String)): "_a table name pattern; must match the table name as it is stored in the database_" – Mark Rotteveel May 29 '13 at 06:07
0

You're correct, you will use a DatabaseMetaData object, and then use its getColumns() method. For instance:

DatabaseMetaData dbm = connection.getMetaData();
ResultSet columns = meta.getColumns(null, "Schema Name", "Table Name", null);

Note that the middle two parameters specify which schema and which table you want the columns of, respectively. (if you pass null for these parameters, your ResultSet will include all columns in all tables in all schemas on your database.

drew moore
  • 31,565
  • 17
  • 75
  • 112
0
  1. execute a query, get ResultSet Object rs
  2. get ResultSetMetaData Object : ResultSetMetaData rsd = rs.getMetaData()
  3. get Column count:

    int columnCount = rsd.getColumnCount();  
    for(int i = 1; i <= columnCount; i++) {  
        System.out.println(rss.getColumnName(i));  
    }
    
Linus Caldwell
  • 10,908
  • 12
  • 46
  • 58
mylxsw
  • 86
  • 2
  • 4