MySQL &Java - 获取最后插入值的 id (JDBC) [英] MySQL & Java - Get id of the last inserted value (JDBC)

查看:17
本文介绍了MySQL &Java - 获取最后插入值的 id (JDBC)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

Hi, I'm using JDBC to connect on database through out Java.

现在,我执行一些插入查询,我需要获取最后插入值的 id(因此,在 stmt.executeUpdate 之后).

Now, I do some insert query, and I need to get the id of last inserted value (so, after a stmt.executeUpdate).

我不需要像 SELECT id FROM table ORDER BY id DESC LIMIT 1 这样的东西,因为我可能有并发问题.

I don't need something like SELECT id FROM table ORDER BY id DESC LIMIT 1, because I may have concurrency problems.

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

I Just need to retrieve the id associated to the last insertion (about my instance of the Statement).

我试过了,但似乎它在 JDBC 上不起作用:

I tried this, but seems it doesn't work on 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;
}

事实上,每次risultato = -1,我都会得到java.sql.SQLException:未请求生成的密钥.您需要将 Statement.RETURN_GENERATED_KEYS 指定为 Statement.executeUpdate() 或 Connection.prepareStatement().

In fact, every time risultato = -1, and I get java.sql.SQLException: Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate() or Connection.prepareStatement().

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

How can I fix this problem? Thanks Stackoverflow People :)

推荐答案

你难道不只是改变一下:

Wouldn't you just change:

numero = stmt.executeUpdate(query);

到:

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

查看 JDBC 的文档 Statement 接口.

Take a look at the documentation for the JDBC Statement interface.

更新:显然,这个答案存在很多混淆,但我的猜测是混淆的人并没有在提出的问题的上下文中阅读它.如果您采用 OP 在他的问题中提供的代码并替换我建议的单行(第 6 行),一切都会正常进行.numero 变量完全无关,它的值在设置后永远不会被读取.

Update: Apparently there is a lot of confusion about this answer, but my guess is that the people that are confused are not reading it in the context of the question that was asked. If you take the code that the OP provided in his question and replace the single line (line 6) that I am suggesting, everything will work. The numero variable is completely irrelevant and its value is never read after it is set.

这篇关于MySQL &Java - 获取最后插入值的 id (JDBC)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆