知道自动增量字段的值

时间:2014-12-03 12:02:31

标签: sql database java-ee

使用表中的代码插入记录,其中一个字段是自动增量(id)。我如何才能找出刚插入的记录中autoincremented field(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??

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

使用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()

的电话