0

Insert records using code in a table, where one of the fields is autoincremented (id). How I can find out what is the value of autoincremented field (id) on record that I just inserted?

         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 Answers2

0

insert_id can retrieve last inserted id $id=$mysqli->insert_id;

0

Use the 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);
}

Note the call to prepareStatement passing PreparedStatement.RETURN_GENERATED_KEYS and the call to ps.getGeneratedKeys()

a_horse_with_no_name
  • 497,550
  • 91
  • 775
  • 843