简体   繁体   中英

How to get the column name of the primary key through 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.

  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

    \nDatabaseMetaData dm = conn.getMetaData( ); \nResultSet rs = dm.getExportedKeys( "" , "" , "table1" ); \nwhile( rs.next( ) )  \n{     \n  String pkey = rs.getString("PKCOLUMN_NAME"); \n  System.out.println("primary key = " + pkey); \n} \n

    you can also use getCrossReference or getImportedKeys to retrieve primary key

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM