Typically, after inserting an insert operation on MySQL in the app, we need to get the self-increment primary key for the inserted record. This article describes the 4 ways in which the Java environment obtains the value of the record primary key auto_increment after insert:
- The InsertRow () method provided by JDBC2.0
- The Getgeneratedkeys () method provided by JDBC3.0
- Through the SQL Select LAST_INSERT_ID () function
- Through the SQL @ @IDENTITY variable
1. The InsertRow () method provided by JDBC2.0
Since jdbc2.0, this can be done in the following way.
[Java]View Plaincopy
- Statement stmt = null;
- ResultSet rs = null;
- try {
- stmt = Conn.createstatement (Java.sql.ResultSet.TYPE_FORWARD_ONLY, //Create statement
- Java.sql.ResultSet.CONCUR_UPDATABLE);
- Stmt.executeupdate ("DROP TABLE IF EXISTS autoinctutorial");
- Stmt.executeupdate ( //Create demo table
- the CREATE TABLE autoinctutorial ("
- + "Prikey INT not NULL auto_increment,"
- + "DataField VARCHAR (+), PRIMARY KEY (Prikey))";
- rs = stmt.executequery ("Select Prikey, DataField" //Retrieving Data
- + "from autoinctutorial");
- Rs.movetoinsertrow (); //Move cursor to the row to be inserted (pseudo record not created)
- Rs.updatestring ("DataField", "AUTO INCREMENT here?"); //modify content
- Rs.insertrow (); //Insert record
- Rs.last (); //Move cursor to last row
- int autoinckeyfromrs = Rs.getint ("Prikey"); //Get the primary key for the record you just inserted prekey
- Rs.close ();
- rs = null;
- System.out.println ("Key returned for inserted row:"
- + Autoinckeyfromrs);
- } finally {
- //rs,stmt Close () cleanup
- }
Advantages: Early and more general practice
Cons: You need to manipulate resultset cursors, the code is verbose.
2. The Getgeneratedkeys () method provided by JDBC3.0
[Java]View Plaincopy
- Statement stmt = null;
- ResultSet rs = null;
- try {
- stmt = Conn.createstatement (Java.sql.ResultSet.TYPE_FORWARD_ONLY,
- Java.sql.ResultSet.CONCUR_UPDATABLE);
- // ...
- //Omit several lines (create demo table as above example)
- // ...
- Stmt.executeupdate (
- "INSERT into Autoinctutorial (DataField)"
- + "VALUES (' Can I Get the Auto Increment Field? ')",
- Statement.return_generated_keys); //To drive indicates the need to obtain generatedkeys! automatically
- int autoinckeyfromapi =-1;
- rs = Stmt.getgeneratedkeys (); //Get self-increment primary key!
- if (Rs.next ()) {
- Autoinckeyfromapi = Rs.getint (1);
- } Else {
- //Throw an exception from here
- }
- Rs.close ();
- rs = null;
- System.out.println ("Key returned from Getgeneratedkeys ():"
- + Autoinckeyfromapi);
- } finally {...}
This approach requires only 2 steps: 1. Activate auto Get key when Executeupdate, 2. Call Statement's Getgeneratedkeys () interface
Advantages: 1. Easy to operate, code concise 2. jdbc3.0 Standard 3. High efficiency because there is no additional access to the database
In addition, a. Before jdbc3.0, each JDBC driver implementation has its own interface to get the self-increment primary key. In MySQL jdbc2.0 's driverIn Org.gjt.mm.mysql, the Getgeneratedkeys () function is implemented in Org.gjt.mm.mysql.jdbc2.Staement.getGeneratedKeys (). With this direct reference, portability can have a lot of impact. JDBC3.0 through the standard Getgeneratedkeys to make up for this very well. B. About Getgeneratedkeys (), the official website also has more detailed explanation: Oraclejdbcguide
3. Via SQL Select LAST_INSERT_ID ()
[Java]View Plaincopy
- Statement stmt = null;
- ResultSet rs = null;
- try {
- stmt = Conn.createstatement ();
- // ...
- //Omit Build table
- // ...
- Stmt.executeupdate (
- "INSERT into Autoinctutorial (DataField)"
- + "VALUES (' Can I Get the Auto Increment Field? ')");
- int autoinckeyfromfunc =-1;
- rs = stmt.executequery ("Select last_insert_id ()"); //Get Generatedkey through additional queries
- if (Rs.next ()) {
- Autoinckeyfromfunc = Rs.getint (1);
- } Else {
- //Throw an exception from here
- }
- Rs.close ();
- System.out.println ("Key returned from" +
- "' Select last_insert_id () ':" +
- AUTOINCKEYFROMFUNC);
- } finally {...}
There is nothing to say in this way, that is, an extra query function last_insert_id (). Advantages: Simple and convenient disadvantage: the relative JDBC3.0 of Getgeneratedkeys (), requires an additional database query.
Add:1. This function, defined in the mysql5.5 manual, is: "Returns a BIGINT (64-bit) value representing the first automatically generated value SUCCESSF Ully inserted for an auto_increment column as a result of the most recently executed INSERT statement. ". Document Point this2. This function is "thread safe" on the connection dimension. That is, each MySQL connection will have a result of saving last_insert_id () independently, and
that is, when 2 connections execute the INSERT statement at the same time, the last_insert_id () that are called separately do not overwrite each other. For a chestnut: connect a after inserting a table last_insert_id () returns 100, last_insert_id () returns 101 after connection B is inserted into the table, but connection a repeats LAST_INSERT_ID (), always returns 100 instead of 101. This can be verified by monitoring the number of MySQL connections and the execution results, and this does not detail the experimental process. 3. Based on the above point, if you execute the insert simultaneously on the same connection, the return value of the 2 operations may overwrite each other. Because last_insert_id () is the connection level. This, Getgeneratedkeys () is able to do better because getgeneratedkeys () is the statement level. The same connection several times Statement,getgeneratedkeys () are not covered by each other.
4. Via SQL SELECT @ @IDENTITYThis is the same way as the last_insert_id () effect. The official website document says: "This variable was a synonym for the last_insert_id variable. It exists for compatibility and other database systems. You can read their value with SELECT @ @identity, and set it using set identity. "Document Point this
Important additions:Whether a select last_insert_id () or a SELECT @ @IDENTITY, inserting multiple records for an INSERT statement will always return only the generatedkey of the first inserted record. such as:
[Java]View Plaincopy
- INSERT into T VALUES
- (NULL, ' Mary '), (null, ' Jane '), (null, ' Lisa ');
LAST_INSERT_ID (), @ @IDENTITY will return only the generatedkey of the record where ' Mary ' is located
MySQL gets the primary key for the other table