Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting index of inserted rows from a MySQL database

Tags:

java

sql

mysql

jdbc

I'm using Java (jdbc) to interact with a MySQL database. I have table with a primary index which is AUTO INCREMENT. When I insert a row, I need to get the index it just received. How do I do that?

like image 636
Amir Rachum Avatar asked Dec 19 '10 15:12

Amir Rachum


People also ask

How do I find the index in MySQL?

To see indexes for all tables within a specific schema you can use the STATISTICS table from INFORMATION_SCHEMA: SELECT DISTINCT TABLE_NAME, INDEX_NAME FROM INFORMATION_SCHEMA. STATISTICS WHERE TABLE_SCHEMA = 'your_schema'; Removing the where clause will show you all indexes in all schemas.

Can you index with MySQL?

Indexing is a powerful structure in MySQL which can be leveraged to get the fastest response times from common queries. MySQL queries achieve efficiency by generating a smaller table, called an index, from a specified column or set of columns. These columns, called a key, can be used to enforce uniqueness.

How do you check is record inserted or not in MySQL?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL.


2 Answers

From: http://dev.mysql.com/doc/refman/5.0/en/connector-j-usagenotes-basic.html#connector-j-usagenotes-last-insert-id

stmt.executeUpdate(
        "INSERT INTO autoIncTutorial (dataField) "
        + "values ('Can I Get the Auto Increment Field?')",
        Statement.RETURN_GENERATED_KEYS);

//
// Example of using Statement.getGeneratedKeys()
// to retrieve the value of an auto-increment
// value
//

int autoIncKeyFromApi = -1;

rs = stmt.getGeneratedKeys();

if (rs.next()) {
    autoIncKeyFromApi = rs.getInt(1);
} else {

    // throw an exception from here
}

rs.close();

rs = null;
like image 168
John Boker Avatar answered Oct 17 '22 06:10

John Boker


Thanks to John Boker for his excellent response.

If you wish to use a PreparedStatement, you can still use RETURN_GENERATED_KEYS, but you have to apply the commands differently:

PreparedStatement ps = mysql.prepareStatement(
    "INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)",
     Statement.RETURN_GENERATED_KEYS );
ps.setString(1, "My text");
ps.setTimestamp(2, new java.sql.Timestamp(new java.util.Date().getTime()););
ps.setInt(3, 5150);
ps.executeUpdate();
ResultSet results = ps.getGeneratedKeys();
results.next(); // Assume just one auto-generated key; otherwise, use a while loop here
System.out.println(results.getInt(1)); // there should only be 1 column in your results: the value of the auto-generated key
  1. Add the RETURN_GENERATED_KEYS param in the prepareStatement() function.
  2. Get results not from statement.executeUpdate() but from statement.getGeneratedKeys().
like image 3
JellicleCat Avatar answered Oct 17 '22 05:10

JellicleCat