MySQL和Java - 获取最后插入值的ID(JDBC)

mar*_*zzz 87 java mysql jdbc

可能重复:
如何在JDBC中获取插入ID?

嗨,我正在使用JDBC通过Java连接数据库.

现在,我做一些插入查询,我需要获取最后插入值的id(所以,在a之后stmt.executeUpdate).

我不需要类似的东西SELECT id FROM table ORDER BY id DESC LIMIT 1,因为我可能会遇到并发问题.

我只需要检索与最后一次插入相关的id(关于我的Statement实例).

我试过这个,但似乎它不适用于JDBC:

public Integer insertQueryGetId(String query) {
    Integer numero=0;
    Integer risultato=-1;
    try {
        Statement stmt = db.createStatement();
        numero = stmt.executeUpdate(query);

        ResultSet rs = stmt.getGeneratedKeys();
        if (rs.next()){
            risultato=rs.getInt(1);
        }
        rs.close();

        stmt.close();
    } catch (Exception e) {
        e.printStackTrace();
        errore = e.getMessage();
        risultato=-1;
    }
  return risultato;
}
Run Code Online (Sandbox Code Playgroud)

事实上,每一次risultato = -1,我都会得到java.sql.SQLException: Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate() or Connection.prepareStatement().

我该如何解决这个问题?谢谢Stackoverflow人:)

Sea*_*ght 167

你不能改变:

numero = stmt.executeUpdate(query);
Run Code Online (Sandbox Code Playgroud)

至:

numero = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
Run Code Online (Sandbox Code Playgroud)

查看JDBC Statement接口的文档.

更新:显然有很多关于这个答案的混淆,但我的猜测是,那些困惑的人并没有在被问到的问题的背景下阅读它.如果您使用OP提供的代码并替换我建议的单行(第6行),一切都会有效.该numero变量是完全无关的,它被设置后,从来没有读过它的价值.

  • @ wu-lee返回值无关紧要(在OP的问题中,不使用`numero`).你会注意到他迭代了`Statement.getGeneratedKeys()`返回的`ResultSet`.如果您有其他问题,请告诉我. (2认同)
  • 这是错误的...方法executeUpdate返回:(1)SQL数据操作语言(DML)语句的行计数或(2)0表示不返回任何内容的SQL语句.您必须创建结果集并获取最后一个ID,如下所示:rs = st.getGeneratedKeys(); if(rs.next()){insertId = rs.getInt(1); } (2认同)

Buh*_*ndi 132

或者你可以这样做:

Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
numero = stmt.executeUpdate();

ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
    risultato=rs.getInt(1);
}
Run Code Online (Sandbox Code Playgroud)

但是请使用Sean Bright的答案代替你的场景.

  • 我知道我迟到了2年,但谢谢你:)这个有效:D (2认同)