简体   繁体   English

Java jdbc获取生成的键的列名

[英]Java jdbc get column names of generated keys

I've inserted a record with a composite primary key in table via jdbc and got generated values of primary key. 我通过jdbc在表中插入了一个带有复合主键的记录,并获得了主键的生成值。

pm = connection.prepareStatement(strQuery,Statement.RETURN_GENERATED_KEYS);
pm.executeUpdate();
ResultSet rsInsert = pm.getGeneratedKeys();
if(rsInsert != null && rsInsert.next()){
    int count = rsInsert.getMetaData().getColumnCount();
    Map<String,Object> map = new HashMap<>();
    for(int i = 1;i <=count;i++)
    {
        Object value = rsInsert.getObject(i);
    }
}

How can I get the column names of generated values? 如何获取生成值的列名? Thanks 谢谢

If you had examined the ResultSetMetaData you're getting with rsInsert.getMetaData() you might have seen getColumnLabel(int) which will return the suggested name at a given column number. 如果您已经检查了使用rsInsert.getMetaData()获得的ResultSetMetaData ,您可能已经看到了getColumnLabel(int) ,它将返回给定列号的建议名称。

// You are getting the Generated Keys here.
pm = connection.prepareStatement(strQuery,Statement.RETURN_GENERATED_KEYS);
pm.executeUpdate();
ResultSet rsInsert = pm.getGeneratedKeys(); // <-- This ResultSet is from the
                                            // insert. Not a standard Query.
if(rsInsert != null && rsInsert.next()){
  int count = rsInsert.getMetaData().getColumnCount();
  Map<String,Object> map = new HashMap<>();
  for(int i = 1;i <=count;i++)
  {
    String colName = rsInsert.getMetaData().getColumnLabel(i); // or ColumnName
    Object value = rsInsert.getObject(i);
  }
}

Edit 编辑

Obviously, if your JDBC driver doesn't follow the Javadoc specification in getGeneratedKeys ("Retrieves any auto-generated keys created as a result of executing this Statement object. If this Statement object did not generate any keys, an empty ResultSet object is returned.") then your results may differ. 显然,如果您的JDBC驱动程序不遵循getGeneratedKeys中的Javadoc规范(“检索由于执行此Statement对象而创建的任何自动生成的键。如果此Statement对象未生成任何键,则返回空的ResultSet对象。 “)那么你的结果可能会有所不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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