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

后端 未结 1 1387
小鲜肉
小鲜肉 2021-01-04 18:45

I have the code as follows:

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

while(rs.next()){
            


        
相关标签:
1条回答
  • 2021-01-04 19:01
    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

    0 讨论(0)
提交回复
热议问题