【问题标题】:Get last inserted auto increment id in mysql在mysql中获取最后插入的自动增量ID
【发布时间】:2012-12-19 16:32:33
【问题描述】:

我正在尝试获取 mysql_insert_id() 之类的 mysql 命令;它检索最后插入的行的 auto_increment id。我该怎么做才能在 Java 中获得它?

rs = st.executeQuery("select last_insert_id() from schedule");
lastid = rs.getString("last_insert_id()");

我的 lastid 被声明为 INT。我不知道在 rs.get 中使用什么以及参数..

【问题讨论】:

    标签: java mysql


    【解决方案1】:

    另一种选择:

    SELECT id FROM table_name ORDER BY id DESC LIMIT 1;

    【讨论】:

      【解决方案2】:

      您可以使用以下查询来获取最后插入行的最后一个 auto_incremented ID。

      SELECT (max(auto_incr_id)) from table_name;
      

      【讨论】:

        【解决方案3】:

        请参阅this 帖子以获得答案和解释

        Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
        numero = stmt.executeUpdate();
        
        ResultSet rs = stmt.getGeneratedKeys();
        if (rs.next()){
            risultato=rs.getInt(1);
        }
        

        【讨论】:

          【解决方案4】:

          为什么不

          SELECT MAX(id) FROM schedule
          

          如果您的列的 id 名称与 id 不同,则需要在上述查询中相应地替换它。

          你可以像这样使用它:

          rs = st.executeQuery("SELECT MAX(id) AS id FROM schedule");
          int lastid = rs.getInt("id");
          

          【讨论】:

          • 我没想到.. 哈哈.. 上次用mysql_insert_id(); 做PHP,突然切换到java,所以我只关注它。感谢您的建议。 :)
          • int lastid = rs.getInt("id"); 将抛出错误,因为id 不存在。您应该首先在您的选择语句中添加一个别名。 rs = st.executeQuery("SELECT MAX(id) id FROM schedule");
          • @JW。谢谢你的提示。更新了我的答案。
          • 你不应该依赖 max(id),因为另一个线程可以在你的 insert 和 select 语句之间插入一个新行,你会得到错误的 id。
          • 是的,同样适用于 mysql_inserted_id 和 last_inserted_id 函数,这也可能由于其他线程上的竞争条件而导致问题,特别是考虑到通常 Web 应用程序共享相同的数据库用户。
          【解决方案5】:

          使用 JDBC,可以使用 Connection.PreparedStatement(query, int) 方法。

          PreparedStatement pstmt = conn.prepareStatement(Query, Statement.RETURN_GENERATED_KEYS);  
          pstmt.executeUpdate();  
          ResultSet keys = pstmt.getGeneratedKeys();    
          keys.next();  
          key = keys.getInt(1);
          

          【讨论】:

          • 我试过这个方法,但它总是返回 1。我不知何故认为这是为了检查它是否向数据库中插入了任何查询?
          • @Maki92 我不太明白你的评论。这段代码只是从你的 table 返回最后一个 auto-increment_id 。顺便说一句,ASAIK 这是使用 JDBC 的标准方式。
          • 我见过有人使用它,但他们面临的问题和我的一样。代码总是从表中返回 1。
          • @Maki92 我很确定这是他们代码中的问题。我自己使用它,从来没有真正遇到过这样的问题.. :)
          • 我有确切的问题。不管真正的索引是什么,它总是返回 1。
          【解决方案6】:

          尝试使用别名

          rs = st.executeQuery("select last_insert_id() as last_id from schedule");
          lastid = rs.getString("last_id");
          

          【讨论】:

          • 为什么要加FROM语句?这是有害的,因为如果您的表包含 2 行,您将得到 2 行结果。 “选择 LAST_INSERT_ID();”够了。
          • 您可以调用 rs.getString("last_id") 来代替 rs.getString(1)。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多