有没有办法从预准备语句中检索自动增量ID [英] Is there a way to retrieve the autoincrement ID from a prepared statement
本文介绍了有没有办法从预准备语句中检索自动增量ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当使用带有预准备语句的java查询时,是否有办法从数据库查询中检索自动生成的密钥。
Is there a way to retrieve the auto generated key from a DB query when using a java query with prepared statements.
例如,我知道AutoGeneratedKeys可以如下工作。
For example, I know AutoGeneratedKeys can work as follows.
stmt = conn.createStatement();
stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
if(returnLastInsertId) {
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
auto_id = rs.getInt(1);
}
但是。如果我想使用准备好的Statement进行插入,该怎么办?
However. What if I want to do an insert with a prepared Statement.
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql);
//this is an error
stmt.executeUpdate(Statement.RETURN_GENERATED_KEYS);
if(returnLastInsertId) {
//this is an error since the above is an error
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
auto_id = rs.getInt(1);
}
有没有办法做到这一点,我不知道。从javadoc看来,PreparedStatements无法返回自动生成的ID。
Is there a way to do this that I don't know about. It seems from the javadoc that PreparedStatements can't return the Auto Generated ID.
推荐答案
是的。请参见此处。第7.1.9节。将您的代码更改为:
Yes. See here. Section 7.1.9. Change your code to:
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.executeUpdate();
if(returnLastInsertId) {
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
auto_id = rs.getInt(1);
}
这篇关于有没有办法从预准备语句中检索自动增量ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文