使用@JdbcInsert时检索自动增量值 [英] Retrieving autoincrement value when using @JdbcInsert

查看:73
本文介绍了使用@JdbcInsert时检索自动增量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将行存储在主键为自动增量的DB2数据库表中.这可以正常工作,但是在成功插入行后,我无法解决如何检索主键值以进行进一步处理的问题.您如何实现的? @JdbcInsert仅返回已插入的行数...

I'm trying to store a row in a DB2 database table where the primary key is an autoincrement. This works fine but I'm having trouble wrapping my head around how to retrieve the primary key value for further processing after successfully inserting the row. How do you achieve this? @JdbcInsert only returns the amount of rows that were inserted ...

推荐答案

由于SSJS似乎没有办法做到这一点(至少对我而言),因此我将这一特殊的逻辑从我的SSJS控制器移到了我为JDBC相关任务创建的Java帮助器bean. 声明可以退回生成的密钥(使用方法 executeUpdate()).因此,我仍然通过@JdbcGetConnection创建我的连接,但随后将其提交到Bean中.这是bean有趣的部分:

Since there does not seem to be a way to do this with SSJS (at least to me), I moved this particular piece of logic from my SSJS controller to a Java helper bean I created for JDBC related tasks. A Statement is capable of handing back generated keys (using the method executeUpdate()). So I still create my connection via @JdbcGetConnection, but then hand it in into the bean. This is the interesting part of the bean:

/**
 * SQL contains the INSERT Statement
 */    
public int executeUpdate(Connection conn, String SQL){

  int returnVal;
  Statement stmt = conn.createStatement();

  stmt.executeUpdate(SQL,
    Statement.RETURN_GENERATED_KEYS);

  if(!conn.getAutoCommit()) conn.commit();

  ResultSet keys = stmt.getGeneratedKeys();

  if(keys.next()){
    returnVal = keys.getInt(1);
  } else {
    returnVal = -1;
  }

  return returnVal;
}

当然,如果一次插入多个行,则需要更改密钥检索处理.

If you insert more than one row at a time, you'll need to change the key retrieval handling, of course.

这篇关于使用@JdbcInsert时检索自动增量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆