【问题标题】:Derby - LAST_INSERT_ID() doesn't work with JDBCDerby - LAST_INSERT_ID() 不适用于 JDBC
【发布时间】:2017-03-01 10:35:56
【问题描述】:

在使用带有 spring 框架的 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: Syntax error: Encountered "" at line 1, column 29."

【问题讨论】:

  • 如果您直接对数据库引擎执行该查询,您会得到正确的结果,对吧?
  • 只是猜测:你能用SELECT LAST_INSERT_ID() as ID from dual试试吗?
  • @Hakerman 它给了我相同的“语法错误:在第 1 行第 29 列遇到“”。”
  • @Insac 它告诉我双重不存在
  • 抱歉,您使用的是什么 RDBMS?

标签: derby spring-jdbc


【解决方案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());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    • 2014-07-02
    • 2013-12-02
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 2013-04-13
    相关资源
    最近更新 更多