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

查看:280
本文介绍了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 :)

推荐答案

你不会改变:

numero = stmt.executeUpdate(query);

to:

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天全站免登陆