JDBC 3种获得mysql插入数据的自增字段值的方法
2015-01-22 11:20
706 查看
1. Retrieving AUTO_INCREMENT Column Values using Statement.getGeneratedKeys()
2. Retrieving AUTO_INCREMENT Column Values using SELECT LAST_INSERT_ID()
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager
.getConnection("jdbc:mysql://localhost:3306/test","root", "admin");
stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_UPDATABLE);
stmt.executeUpdate("INSERT INTO autoIncTutorial (dataField) " +
"values ('')", Statement.RETURN_GENERATED_KEYS);
int autoIncKeyFromApi = -1;
rs = stmt.getGeneratedKeys();
if (rs.next()) {
autoIncKeyFromApi = rs.getInt(1);
} else {
// throw an exception from here
}
stmt.executeUpdate("INSERT INTO autoIncTutorial (dataField) " + "values ('')");
int autoIncKeyFromFunc = -1;
rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");
if (rs.next()) {
autoIncKeyFromFunc = rs.getInt(1);
} else {
// throw an exception from here
}
http://blog.sina.com.cn/s/blog_4cc16fc50100c6sz.html
mysql 官方说明:
http://dev.mysql.com/doc/connector-j/en/connector-j-usagenotes-last-insert-id.html
6.4 Retrieving
Before version 3.0 of the JDBC API, there was no standard way of retrieving key values from databases that supported auto increment or identity columns. With older JDBC drivers for MySQL, you could always use a MySQL-specific method on the
retrieve
Example 6.8 Connector/J: Retrieving
Example 6.9 Connector/J: Retrieving
Example 6.10 Connector/J: Retrieving
Running the preceding example code should produce the following output:
At times, it can be tricky to use the
2. Retrieving AUTO_INCREMENT Column Values using SELECT LAST_INSERT_ID()
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager
.getConnection("jdbc:mysql://localhost:3306/test","root", "admin");
stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_UPDATABLE);
stmt.executeUpdate("INSERT INTO autoIncTutorial (dataField) " +
"values ('')", Statement.RETURN_GENERATED_KEYS);
int autoIncKeyFromApi = -1;
rs = stmt.getGeneratedKeys();
if (rs.next()) {
autoIncKeyFromApi = rs.getInt(1);
} else {
// throw an exception from here
}
stmt.executeUpdate("INSERT INTO autoIncTutorial (dataField) " + "values ('')");
int autoIncKeyFromFunc = -1;
rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");
if (rs.next()) {
autoIncKeyFromFunc = rs.getInt(1);
} else {
// throw an exception from here
}
http://blog.sina.com.cn/s/blog_4cc16fc50100c6sz.html
mysql 官方说明:
http://dev.mysql.com/doc/connector-j/en/connector-j-usagenotes-last-insert-id.html
6.4 Retrieving
AUTO_INCREMENT
Column Values through JDBC
Before version 3.0 of the JDBC API, there was no standard way of retrieving key values from databases that supported auto increment or identity columns. With older JDBC drivers for MySQL, you could always use a MySQL-specific method on theStatementinterface, or issue the query
SELECT LAST_INSERT_ID()after issuing an
INSERTto a table that had an
AUTO_INCREMENTkey. Using the MySQL-specific method call isn't portable, and issuing a
SELECTto get the
AUTO_INCREMENTkey's value requires another round-trip to the database, which isn't as efficient as possible. The following code snippets demonstrate the three different ways to
retrieve
AUTO_INCREMENTvalues. First, we demonstrate the use of the new JDBC 3.0 method
getGeneratedKeys()which is now the preferred method to use if you need to retrieve
AUTO_INCREMENTkeys and have access to JDBC 3.0. The second example shows how you can retrieve the same value using a standard
SELECT LAST_INSERT_ID()query. The final example shows how updatable result sets can retrieve the
AUTO_INCREMENTvalue when using the
insertRow()method.
Example 6.8 Connector/J: Retrieving
AUTO_INCREMENTcolumn values using
Statement.getGeneratedKeys()
Statement stmt = null; ResultSet rs = null; try { // // Create a Statement instance that we can use for // 'normal' result sets assuming you have a // Connection 'conn' to a MySQL database already // available stmt = conn.createStatement(); // // Issue the DDL queries for the table for this example // stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTutorial"); stmt.executeUpdate( "CREATE TABLE autoIncTutorial (" + "priKey INT NOT NULL AUTO_INCREMENT, " + "dataField VARCHAR(64), PRIMARY KEY (priKey))"); // // Insert one row that will generate an AUTO INCREMENT // key in the 'priKey' field // 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 } System.out.println("Key returned from getGeneratedKeys():" + autoIncKeyFromApi); } finally { if (rs != null) { try { rs.close(); } catch (SQLException ex) { // ignore } } if (stmt != null) { try { stmt.close(); } catch (SQLException ex) { // ignore } } }
Example 6.9 Connector/J: Retrieving
AUTO_INCREMENTcolumn values using
SELECT LAST_INSERT_ID()
Statement stmt = null; ResultSet rs = null; try { // // Create a Statement instance that we can use for // 'normal' result sets. stmt = conn.createStatement(); // // Issue the DDL queries for the table for this example // stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTutorial"); stmt.executeUpdate( "CREATE TABLE autoIncTutorial (" + "priKey INT NOT NULL AUTO_INCREMENT, " + "dataField VARCHAR(64), PRIMARY KEY (priKey))"); // // Insert one row that will generate an AUTO INCREMENT // key in the 'priKey' field // stmt.executeUpdate( "INSERT INTO autoIncTutorial (dataField) " + "values ('Can I Get the Auto Increment Field?')"); // // Use the MySQL LAST_INSERT_ID() // function to do the same thing as getGeneratedKeys() // int autoIncKeyFromFunc = -1; rs = stmt.executeQuery("SELECT LAST_INSERT_ID()"); if (rs.next()) { autoIncKeyFromFunc = rs.getInt(1); } else { // throw an exception from here } System.out.println("Key returned from " + "'SELECT LAST_INSERT_ID()': " + autoIncKeyFromFunc); } finally { if (rs != null) { try { rs.close(); } catch (SQLException ex) { // ignore } } if (stmt != null) { try { stmt.close(); } catch (SQLException ex) { // ignore } } }
Example 6.10 Connector/J: Retrieving
AUTO_INCREMENTcolumn values in
Updatable ResultSets
Statement stmt = null; ResultSet rs = null; try { // // Create a Statement instance that we can use for // 'normal' result sets as well as an 'updatable' // one, assuming you have a Connection 'conn' to // a MySQL database already available // stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_UPDATABLE); // // Issue the DDL queries for the table for this example // stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTutorial"); stmt.executeUpdate( "CREATE TABLE autoIncTutorial (" + "priKey INT NOT NULL AUTO_INCREMENT, " + "dataField VARCHAR(64), PRIMARY KEY (priKey))"); // // Example of retrieving an AUTO INCREMENT key // from an updatable result set // rs = stmt.executeQuery("SELECT priKey, dataField " + "FROM autoIncTutorial"); rs.moveToInsertRow(); rs.updateString("dataField", "AUTO INCREMENT here?"); rs.insertRow(); // // the driver adds rows at the end // rs.last(); // // We should now be on the row we just inserted // int autoIncKeyFromRS = rs.getInt("priKey"); System.out.println("Key returned for inserted row: " + autoIncKeyFromRS); } finally { if (rs != null) { try { rs.close(); } catch (SQLException ex) { // ignore } } if (stmt != null) { try { stmt.close(); } catch (SQLException ex) { // ignore } } }
Running the preceding example code should produce the following output:
Key returned from getGeneratedKeys(): 1 Key returned from SELECT LAST_INSERT_ID(): 1 Key returned for inserted row: 1
At times, it can be tricky to use the
SELECT LAST_INSERT_ID()query, as that function's value is scoped to a connection. So, if some other query happens on the same connection, the value is overwritten. On the other hand, the
getGeneratedKeys()method is scoped by the
Statementinstance, so it can be used even if other queries happen on the same connection, but not on the same
Statementinstance.
相关文章推荐
- JDBC 3种获得mysql插入数据的自增字段值的方法
- JDBC 3种获得mysql插入数据的自增字段值的方法
- JDBC 3种获得mysql插入数据的自增字段值的方法
- JDBC 批量插入Mysql 字段值采用随机字符 100万条数据
- [转载]mysql获得刚插入数据的ID方法(自增列ID)
- 使用JDBC插入多数据测试的3种实现方法
- 当插入数据失败时,防止mysql自增长字段的自增长的方法
- 使用JDBC插入多数据测试的3种实现方法
- Mysql 通过JDBC快速插入数据方法
- mysql获得刚插入数据的ID方法--转载
- MySQL 中将一个表的数据插入另外一个表的方法
- php向MySQL插入数据不全 解决方法
- 从MySQL中获得数据表auto_increment值的方法
- Spring中JDBC插入数据后获得该记录的ID
- SQLServer中获得刚插入数据中主键值的方法
- mysql 数据插入优化方法
- mysql 复制表数据,表结构的3种方法
- mysql获得即将添加数据的自动编号id方法
- PHP插入数据到Mysql出现乱码的解决方法
- mysql如果数据不存在,则插入新数据,否则更新的实现方法