使用@JdbcInsert时检索自动增量值

编程入门 行业动态 更新时间:2024-10-28 13:16:49
本文介绍了使用@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()) connmit(); 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时检索自动增量值

本文发布于:2023-11-13 09:10:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1583974.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:增量   JdbcInsert

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!