JDBC 3种获得mysql插入数据的自增字段值的方法
2007-03-13 13:36
941 查看
获得mysql auto increment字段值的3种方法
居然在mysql自带的docs中找到了。下面测试程序可以运行
1。Retrieving AUTO_INCREMENT Column Values using Statement.getGeneratedKeys()
2。Retrieving AUTO_INCREMENT Column Values using SELECT LAST_INSERT_ID()
3。Retrieving AUTO_INCREMENT Column Values in Updatable ResultSets
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class RetrievAutoIncrementTest {
public void init() throws Exception {
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/test?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&mysqlEncoding=utf8", "root", "******");
//
// Issue the DDL queries for the table for this example
//
stmt = conn.createStatement();
stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTutorial");
stmt.executeUpdate(
"CREATE TABLE autoIncTutorial ("
+ "priKey INT NOT NULL AUTO_INCREMENT, "
+ "dataField VARCHAR(64), PRIMARY KEY (priKey))");
} finally {
if( rs != null ) {try{rs.close();}catch(Exception e){}}
if( stmt != null ) {try{stmt.close();}catch(Exception e){}}
if( conn != null ) {try{conn.close();}catch(Exception e){}}
}
}
public void test1() throws Exception {
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/test?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&mysqlEncoding=utf8", "root", "******");
//
// 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(java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_UPDATABLE);
//
// Insert one row that will generate an AUTO INCREMENT
// key in the 'priKey' field
//
for(int i=0; i<10; i++) {
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;
System.out.println("Key returned from getGeneratedKeys():"
+ autoIncKeyFromApi);
}
} finally {
if( rs != null ) {try{rs.close();}catch(Exception e){}}
if( stmt != null ) {try{stmt.close();}catch(Exception e){}}
if( conn != null ) {try{conn.close();}catch(Exception e){}}
}
}
public void test2() throws Exception {
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
//
// Create a Statement instance that we can use for
// 'normal' result sets.
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/test?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&mysqlEncoding=utf8", "root", "******");
stmt = conn.createStatement();
//
// Insert one row that will generate an AUTO INCREMENT
// key in the 'priKey' field
//
for(int i=0; i<10; i++) {
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
}
rs.close();
System.out.println("Key returned from " + "'SELECT LAST_INSERT_ID()': "
+ autoIncKeyFromFunc);
}
} finally {
if( rs != null ) {try{rs.close();}catch(Exception e){}}
if( stmt != null ) {try{stmt.close();}catch(Exception e){}}
if( conn != null ) {try{conn.close();}catch(Exception e){}}
}
}
public void test3() throws Exception {
Statement stmt = null;
ResultSet rs = null;
Connection conn = 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
//
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/test?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&mysqlEncoding=utf8", "root", "******");
stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_UPDATABLE);
for(int i=0; i<10; i++) {
//
// 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");
rs.close();
rs = null;
System.out.println("Key returned for inserted row: "
+ autoIncKeyFromRS);
}
} finally {
if( rs != null ) {try{rs.close();}catch(Exception e){}}
if( stmt != null ) {try{stmt.close();}catch(Exception e){}}
if( conn != null ) {try{conn.close();}catch(Exception e){}}
}
}
/**
* @param args
*/
public static void main(String[] args) throws Exception {
RetrievAutoIncrementTest test = new RetrievAutoIncrementTest();
test.init();
test.test1();
test.test2();
test.test3();
}
}
居然在mysql自带的docs中找到了。下面测试程序可以运行
1。Retrieving AUTO_INCREMENT Column Values using Statement.getGeneratedKeys()
2。Retrieving AUTO_INCREMENT Column Values using SELECT LAST_INSERT_ID()
3。Retrieving AUTO_INCREMENT Column Values in Updatable ResultSets
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class RetrievAutoIncrementTest {
public void init() throws Exception {
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/test?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&mysqlEncoding=utf8", "root", "******");
//
// Issue the DDL queries for the table for this example
//
stmt = conn.createStatement();
stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTutorial");
stmt.executeUpdate(
"CREATE TABLE autoIncTutorial ("
+ "priKey INT NOT NULL AUTO_INCREMENT, "
+ "dataField VARCHAR(64), PRIMARY KEY (priKey))");
} finally {
if( rs != null ) {try{rs.close();}catch(Exception e){}}
if( stmt != null ) {try{stmt.close();}catch(Exception e){}}
if( conn != null ) {try{conn.close();}catch(Exception e){}}
}
}
public void test1() throws Exception {
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/test?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&mysqlEncoding=utf8", "root", "******");
//
// 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(java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_UPDATABLE);
//
// Insert one row that will generate an AUTO INCREMENT
// key in the 'priKey' field
//
for(int i=0; i<10; i++) {
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;
System.out.println("Key returned from getGeneratedKeys():"
+ autoIncKeyFromApi);
}
} finally {
if( rs != null ) {try{rs.close();}catch(Exception e){}}
if( stmt != null ) {try{stmt.close();}catch(Exception e){}}
if( conn != null ) {try{conn.close();}catch(Exception e){}}
}
}
public void test2() throws Exception {
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
//
// Create a Statement instance that we can use for
// 'normal' result sets.
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/test?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&mysqlEncoding=utf8", "root", "******");
stmt = conn.createStatement();
//
// Insert one row that will generate an AUTO INCREMENT
// key in the 'priKey' field
//
for(int i=0; i<10; i++) {
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
}
rs.close();
System.out.println("Key returned from " + "'SELECT LAST_INSERT_ID()': "
+ autoIncKeyFromFunc);
}
} finally {
if( rs != null ) {try{rs.close();}catch(Exception e){}}
if( stmt != null ) {try{stmt.close();}catch(Exception e){}}
if( conn != null ) {try{conn.close();}catch(Exception e){}}
}
}
public void test3() throws Exception {
Statement stmt = null;
ResultSet rs = null;
Connection conn = 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
//
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/test?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&mysqlEncoding=utf8", "root", "******");
stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_UPDATABLE);
for(int i=0; i<10; i++) {
//
// 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");
rs.close();
rs = null;
System.out.println("Key returned for inserted row: "
+ autoIncKeyFromRS);
}
} finally {
if( rs != null ) {try{rs.close();}catch(Exception e){}}
if( stmt != null ) {try{stmt.close();}catch(Exception e){}}
if( conn != null ) {try{conn.close();}catch(Exception e){}}
}
}
/**
* @param args
*/
public static void main(String[] args) throws Exception {
RetrievAutoIncrementTest test = new RetrievAutoIncrementTest();
test.init();
test.test1();
test.test2();
test.test3();
}
}
相关文章推荐
- JDBC 3种获得mysql插入数据的自增字段值的方法
- JDBC 3种获得mysql插入数据的自增字段值的方法
- JDBC 3种获得mysql插入数据的自增字段值的方法
- [转载]mysql获得刚插入数据的ID方法(自增列ID)
- JDBC 批量插入Mysql 字段值采用随机字符 100万条数据
- Mysql 通过JDBC快速插入数据方法
- mysql获得刚插入数据的ID方法--转载
- 使用JDBC插入多数据测试的3种实现方法
- 当插入数据失败时,防止mysql自增长字段的自增长的方法
- 使用JDBC插入多数据测试的3种实现方法
- mysql 从一个表中查数据并插入另一个表实现方法
- MongoDB插入数据的3种方法
- mysql 插入数据失败防止自增长主键增长的方法
- Mysql的longblob字段插入数据问题解决
- mysql如果数据不存在,则插入新数据,否则更新的实现方法
- mysql函数之六:mysql插入数据后返回自增ID的方法,last_insert_id(),selectkey
- JAVA中使用JDBC插入大量mysql中的数据
- JAVA中使用JDBC插入大量mysql中的数据
- mysql导入导出数据中文乱码解决方法小结(1、navicat导入问题已解决,创建连接后修改连接属性,选择高级->将使用Mysql字符集复选框去掉,下拉框选择GBK->导入sql文件OK;2、phpmyadmin显示乱码的问题也解决,两步:1.将sql文件以utf8的字符集编码另存,2.将文件中sql语句中的字段字符集编码改成utf8,导入OK)
- mysql 插入数据后返回当前的自增ID方法