我无法使用带弹簧框架的JdbcTemplate获取最后一个插入ID,在使用last_insert_id()函数之前,我已经搜索了很多其他方法,但是没有使用它。 顺便说一下,我的桌子有
private static final String insertResponse =
"INSERT INTO response (" +
" idReceiver) " +
"VALUES (?)";
public static void saveResponse(Response response, User user) {
dataSource = getDataSource();
JdbcTemplate template = new JdbcTemplate(dataSource);
//"select id from users where username ='"+ user.getUsername +"'";
// define query arguments
Object[] params = new Object[] { 1 };
int[] responseTypes = new int[] { Types.INTEGER };
int row = template.update(insertResponse, params, responseTypes);
if (row >0){
SqlRowSet rowSet = template.queryForRowSet("SELECT LAST_INSERT_ID() AS id");
int lastInsertedID=0;
if (rowSet.next())
lastInsertedID = rowSet.findColumn("id");
System.out.println("last insert row is : "+lastInsertedID);
}
我的响应表是由此命令创建的:
CREATE TABLE RESPONSE (
ID INT NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY
(START WITH 1, INCREMENT BY 1),
idReceiver INT NOT NULL
);
当我运行此代码时,我的JVM说"嘿,你有这个例外: org.springframework.jdbc.BadSqlGrammarException:StatementCallback;错误的SQL语法[SELECT LAST_INSERT_ID()AS id];嵌套异常是java.sql.SQLSyntaxErrorException:语法错误:遇到""在第1行,第29栏。"
答案 0 :(得分:1)
如果有人遇到同样的问题,我已按照answer ..
解决了问题 KeyHolder keyHolder = new GeneratedKeyHolder();
template.update(
new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(java.sql.Connection connection) throws SQLException {
PreparedStatement ps =
connection.prepareStatement(insertResponse, new String[] {"id"});
ps.setInt(1, 1);
return ps;
}
},
keyHolder);
System.out.println("last inserted id is "+keyHolder.getKey());