How to return the ID of a record right after it is inserted?

Asked

Viewed 11,171 times

8

I am making a Java application in conjunction with a Mysql database and would like to know what would be the best command to return an auto database increment ID right after the record is inserted.

My application will work with multiple simultaneous access to the database and would like in a way that no errors occur of the return type a wrong ID that was entered by another user.

I’m using JDBC and I get the connection back this way:

private static final String URL = "jdbc:mysql://localhost/exemplows";
private static final String USER = "XXXXXXXX";
private static final String SENHA = "XXXXXXX";

public static Connection obtemConexao() throws SQLException {
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block e.printStackTrace();
    }
    return DriverManager.getConnection(URL, USER, SENHA);
}
  • You are using JDBC "pure" or something else, like JPA/Hibernate?

  • private Static final String URL = "jdbc:mysql://localhost/exemplows"; private Static final String USER = "XXXXXXXX"; private Static final String PASSWORD = "XXXXXXX"; public Static Connection obtaineConexao() throws Sqlexception { Try { Class.forName("com.mysql.jdbc.Driver"); } catch (Classnotfoundexception e) { // TODO Auto-generated catch block e. printStackTrace(); } Return Drivermanager.getConnection(URL, USER, PASSWORD); }

  • My connection is this

  • Okay, you’re probably using PreparedStatement so I already include an answer for you.

  • I found this command on the internet ppst.getGeneratedKeys(). getInt("idOrdemCompra"); but not yet tested, does it work without risk of a bug id wrong?

  • Yes, that’s kind of it. See if my answer helps you.

Show 1 more comment

3 answers

12


Yes, there is a way to recover. Starting from how you recover the connection it is possible that you are using something like this to build the statement and do the Insert:

final String sql = "INSERT INTO minha_tabela(coluna_um, coluna_dois) VALUES(?, ?)";
final Connection conn = obtemConexao();
final PreparedStatement ps = conn.prepareStatement(sql);
// seta os valores dos parâmetros
ps.executeUpdate();

Basically what you need to do is change the call from #prepareStatement(sql) for #prepareStatement(sql, Statement.RETURN_GENERATED_KEYS).

This #prepareStatement(sql, Statement.RETURN_GENERATED_KEYS) create a statement which has the ability to recover database generated data such as auto-incremented ids. To use, you can do something like this:

final String sql = "INSERT INTO minha_tabela(coluna_um, coluna_dois) VALUES (?, ?);";
final Connection conn = obtemConexao();
final PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
// seta os valores dos parâmetros
ps.executeUpdate();
final ResultSet rs = ps.getGeneratedKeys();
if (rs.next()) {
    final int lastId = rs.getInt(1);
}

This example considers that you have only one "auto generated" column and recovers its value. You can also call by name, thus:

final int lastId = rs.getInt("id");

If there is more than one "auto generated" column in your table, all of them will be returned.

  • I’m having an exception here in Mysql, it inserts the record but when returning the id it says that the column was not found, I checked here if I typed wrong, but not, this correct , I gave up a Ctrl+c Ctrl+v in the name LINK WITH DEBUG IMAGE http://postimg.org/image/rejapfqzz/

  • @user3777310 this error is because you do not have this column in your table. Or, if so, it is not auto generated. No ResultSet returned only those that are somehow auto generated.

  • 2

    After a while stirring here I managed to make it work, instead of putting the name of the column I put the position so it became easier, because it was just a column I was looking for anyway, thanks there for the help Bruno César

  • I also could not pass the column name as argument. Maybe it is the case to edit this answer

  • 1

    @Micaelferreira the column function depends on the JDBC driver, so like several other specification features, some things don’t work depending on the driver.

4

I’ve done it this way:

    ResultSet resultSet = preparedStatement.executeQuery("SELECT LAST_INSERT_ID()");
        if (resultSet.next()) {
            novoId = resultSet.getInt("LAST_INSERT_ID()");
        }

Executing this code right after insertion will return the last generated id.

1

The generated key in auto_increment does not need to be returned in a Resultset, Following example:

sql = "INSERT INTO tabela1 (ID_CLIENTE,total) VALUES (?,?)";
        try {
            stmt = con.prepareStatement(sql);
            stmt.setInt(1, cliente.getID());
            stmt.setDouble(2, total);
            stmt.execute();
            sql = "SELECT LAST_INSERT_ID() INTO @id";
            stmt = con.prepareStatement(sql);
            stmt.execute();
            sql = "INSERT INTO tabela2 (ID_TABELA1,valor) VALUES (@id,?)";
            stmt = con.prepareStatement(sql);
            stmt.setDouble(1, valor);
            stmt.execute();
            return true;
        } catch (SQLException ex) {
            Logger.getLogger(ValorClienteDAO.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        } finally {
            ConnectionFactoryMySQL.closeConnection(con, stmt, rs);
        }

tested and working.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.