【问题标题】:How to get last inserted ID as Long in java mysql [duplicate]如何在java mysql中获取最后插入的ID为Long [重复]
【发布时间】:2016-06-05 02:36:04
【问题描述】:

我想将最后插入的 ID 设为long。因为我的表的主键是long 数据类型。

这是我的代码:

        Connection connection = null;
        Statement statement = null;
        try {
            String sql = "INSERT INTO testTable(name) VALUES('Anonym')";
            connection = DriverManager.getConnection(DB_URL, USER, PASS);
            statement = connection.createStatement();
            long lastInsertedID = statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
            System.out.println("LAST INSERTED ID = "+lastInsertedID);


        } catch (Exception e) {
            e.printStackTrace();
        }

我已经测试过,当整数的最大值达到时,我得到最后一个作为最后插入的 ID。

顺便说一句,我已经通过了这个post

谢谢。

【问题讨论】:

  • try (ResultSet generatedKeys = statement.getGeneratedKeys()) { generatedKeys.next(); SYstem.out.println(generatedKeys.getLong(1)); } - BalusC

标签: java mysql


【解决方案1】:

试试下面的代码 sn-p:

ResultSet rs= statement.getGeneratedKeys();
if (rs.next()) 
{
   System.out.println("Last Inserted ID = "+rs.getLong(1));
}

这是完整的代码:

        Connection connection = null;
        Statement statement = null;
        try {
            String sql = "INSERT INTO testTable(name) VALUES('Anonym')";
            connection = DriverManager.getConnection(DB_URL, USER, PASS);
            statement = connection.createStatement();
            long lastInsertedID = statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
            ResultSet rs= statement.getGeneratedKeys();
            if (rs.next()) 
            {
              System.out.println("Last Inserted ID = "+rs.getLong(1));
            }    

        } catch (Exception e) {
            e.printStackTrace();
        }

【讨论】:

    猜你喜欢
    • 2011-05-13
    • 2014-01-20
    • 2019-01-16
    • 1970-01-01
    • 2014-07-07
    • 2014-01-09
    • 2010-12-13
    • 2017-10-14
    • 2011-06-01
    相关资源
    最近更新 更多