【问题标题】:Get the latest inserted value for an identity primary key获取标识主键的最新插入值
【发布时间】:2013-05-27 16:32:03
【问题描述】:

我有一个Statement,我在其中向我的数据库中的一个表插入一些值,该表有一个主键,它的名称是:numBon

当我执行插入命令时,我想得到numBon的值。

现在我正在使用这段代码:

Statement st = connection.createStatement();
ResultSet result = st.executeQuery("SELECT MAX(numBon) FROM BonInterne");
int numBon;
if (result.next()) {
            numBon = result.getInt("numBon");
        }

就没有别的办法了吗?

【问题讨论】:

标签: java mysql


【解决方案1】:

使用Statement.getGeneratedKeys() 检索自动生成的值。

Statement st = connection.createStatement();
st.execute("insert into ... "); //query where the server generates a value for
                                 //an auto incremented column
ResultSet rs = st.getGeneratedKeys
int numBon;
if (rs.next()) { 
  numBon = result.getInt(1);
}

【讨论】:

    【解决方案2】:

    这是一个自动增量列吗?假设是,您可以这样做:

    SELECT LAST_INSERT_ID()

    但这与数据库无关。 This article gives a much better answer. 或者您可以查看@eidsonator 的评论以更快地了解如何从插入语句中获取ID。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多