当我通过jdbctemplate在表中插入记录时,如何获取自动增加的id [英] How can I get the autoincremented id when I insert a record in a table via jdbctemplate
本文介绍了当我通过jdbctemplate在表中插入记录时,如何获取自动增加的id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
private void insertIntoMyTable (Myclass m) {
String query = "INSERT INTO MYTABLE (NAME) VALUES (?)";
jdbcTemplate.update(query, m.getName());
}
当上述查询插入记录时, ID
表自动增量中的列。
When the above query inserts a record, the ID
column in the table autoincrements.
有没有办法在插入时获得这个自动递增的ID。所以在这个例子中,我的方法的返回值是 int
Is there a way to get this auto incremented ID back at the time of the insertion. So in this example the return value of my method would be int
推荐答案
查看此参考文献。您可以将jdbcTemplate.update用作:
Check this reference. You can use jdbcTemplate.update as:
编辑
按要求添加导入
EDIT Added imports as asked
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
以下是代码用法:
final String INSERT_SQL = "insert into my_test (name) values(?)";
final String name = "Rob";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(
new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps =
connection.prepareStatement(INSERT_SQL, new String[] {"id"});
ps.setString(1, name);
return ps;
}
},
keyHolder);
// keyHolder.getKey() now contains the generated key
这篇关于当我通过jdbctemplate在表中插入记录时,如何获取自动增加的id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文