【问题标题】:Knowing the value of autoincremented fields了解自增字段的值
【发布时间】:2014-12-03 12:02:31
【问题描述】:

使用代码在表中插入记录,其中一个字段是自动递增的 (id)。如何找出我刚刚插入的记录中的自动增量字段 (id) 的值是多少?

         PreparedStatement ps = null;
    Connection con = null;
    ResultSet rs = null;
    int rows = 0;
    try {
        String SQL_DRV = "org.hsqldb.jdbcDriver";
        String SQL_URL = "jdbc:hsqldb:hsql://localhost/localDB";

                    Class.forName(SQL_DRV);
        con = DriverManager.getConnection(SQL_URL, "sa", "");

                                ps = con.prepareStatement(
                "insert into infousuarios (nombre, apellidos, email) " +
                "values (?, ?, ?)");
        ps.setString(1, name);
        ps.setString(2, surnames);
        ps.setString(3, login+"@micorreo.com");


        rows = ps.executeUpdate();
        // How I can know the value of autoincrement field (id) of the record just enter??

【问题讨论】:

标签: sql database jakarta-ee


【解决方案1】:

使用getGeneratedKeys()

ps = con.prepareStatement(
      "insert into infousuarios (nombre, apellidos, email) " +
      "values (?, ?, ?)", Statement.RETURN_GENERATED_KEYS); 

ps.setString(1, name);
ps.setString(2, surnames);
ps.setString(3, login+"@micorreo.com");

rows = ps.executeUpdate();

ResultSet keys = ps.getGeneratedKeys();
long id = -1;

if (keys.next()) {
  id = rs.getLong(1);
}

注意对prepareStatement 的调用传递PreparedStatement.RETURN_GENERATED_KEYS 和对ps.getGeneratedKeys() 的调用

【讨论】:

    【解决方案2】:

    insert_id 可以检索最后插入的 id $id=$mysqli->insert_id;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-26
      • 2010-11-27
      • 1970-01-01
      • 1970-01-01
      • 2020-04-18
      • 1970-01-01
      相关资源
      最近更新 更多