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??
  • Most databases have a function to retrieve it, usually something like "last insert id" or such. – Erik Dec 03 '14 at 12:07
  • Look this answer http://stackoverflow.com/questions/10353405/how-to-return-last-inserted-auto-incremented-row-id-in-hsql – Simon Sadetsky Dec 03 '14 at 12:11

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