Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the column name of the primary key through jdbc

Tags:

java

jdbc

I have the code as follows:

DatabaseMetaData dmd = connection.getMetaData();
ResultSet rs = dmd.getPrimaryKeys(null, null, tableName);

while(rs.next()){
    primaryKey = rs.getString("COLUMN_NAME");
}

rs is not null while rs.next() always return false, anyone has idea about it? Thanks.

like image 498
Foredoomed Avatar asked Jul 16 '12 14:07

Foredoomed


1 Answers

  1. metadata interface implementation was implemented by driver vendors. It may not be supported by some driver and some db. Here is text from javadoc: Some DatabaseMetaData methods return lists of information in the form of ResultSet objects. Regular ResultSet methods, such as getString and getInt, can be used to retrieve the data from these ResultSet objects. If a given form of metadata is not available, an empty ResultSet will be returned.

  2. table name is case sensitive in oracle

  3. or try the below approach

    DatabaseMetaData dm = conn.getMetaData( );
    ResultSet rs = dm.getExportedKeys( "" , "" , "table1" );
    while( rs.next( ) ) 
    {    
      String pkey = rs.getString("PKCOLUMN_NAME");
      System.out.println("primary key = " + pkey);
    }
    

    you can also use getCrossReference or getImportedKeys to retrieve primary key

like image 102
defender Avatar answered Sep 19 '22 06:09

defender