java 如何通过jdbc获取主键的列名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11506884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:22:44  来源:igfitidea点击:

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

javajdbc

提问by Foredoomed

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.

rs 不是 null 而rs.next()总是 return false,有人知道吗?谢谢。

采纳答案by defender

  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

  1. 元数据接口实现由驱动程序供应商实现。某些驱动程序和某些数据库可能不支持它。这是来自 javadoc 的文本:一些 DatabaseMetaData 方法以 ResultSet 对象的形式返回信息列表。常规 ResultSet 方法(例如 getString 和 getInt)可用于从这些 ResultSet 对象中检索数据。如果给定形式的元数据不可用,则将返回一个空的 ResultSet。

  2. oracle中的表名区分大小写

  3. 或尝试以下方法

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

    您还可以使用 getCrossReference 或 getImportedKeys 来检索主键