常常在使用Hibernate、iBatis時候,當插入一條數據的時候,實體Bean的原空主鍵就 賦上新值了。
在JDBC中,也可以通過變相的手法來做到這點。下面是個測試的小例子。
一、環境
MySQL5.1
mysql-connector-java-5.1.10
jdk1.5
CREATE TABLE book(
code bigint(20) unsigned NOT NULL AUTO_INCREMENT,
kind varchar(45) NOT NULL,
name varchar(45) NOT NULL,
PRIMARY KEY(code, kind)
) ENGINE = InnoDB AUTO_INCREMENT = 1 DEFAULT CHARSET = latin1
二、獲取自增主鍵
import lavasoft.common.DBToolkit;
import java.sql.*;
/**
* JDBC獲取新增記錄的主鍵
*
* @author leizhimin 2009-12-4 13:20:15
*/
public class InsertKeyTest {
public static void main(String[] args) {
insertWithStaticSQL();
insertWithParperedSQL();
}
/**
* 預定義SQL模式,獲取新增記錄的主鍵
*/
public static void insertWithParperedSQL() {
Connection conn = null;
try {
conn = DBToolkit.getConnection();
String sql = "insert into testdb.user (name, pswd) values(?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql, Statement.NO_GENERATED_KEYS);
pstmt.setString(1, "laozhang");
pstmt.setString(2, "111111");
pstmt.executeUpdate();
//檢索由於執行此 Statement 對象而創建的所有自動生成的鍵
ResultSet rs = pstmt.getGeneratedKeys();
if (rs.next()) {
//知其僅有一 列,故獲取第一列
Long id = rs.getLong(1);
System.out.println("-----預定義SQL模式-----id = " + id);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBToolkit.closeConnection (conn);
}
}
/**
* 靜態SQL模式,獲取新增記錄的主鍵
*/
public static void insertWithStaticSQL() {
Connection conn = null;
try {
conn = DBToolkit.getConnection();
String sql = "insert into testdb.user (name, pswd) values('ttttt','121')";
PreparedStatement pstmt = conn.prepareStatement(sql, Statement.NO_GENERATED_KEYS);
pstmt.executeUpdate();
//檢索由於執行此 Statement 對象而創建的所有自動生成的鍵
ResultSet rs = pstmt.getGeneratedKeys();
if (rs.next()) {
//知其僅有一 列,故獲取第一列
Long id = rs.getLong(1);
System.out.println("-----靜態SQL模式-----id = " + id);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBToolkit.closeConnection (conn);
}
}
}
執行結果:
-----靜態SQL模式-----id = 8
-----預定義SQL模式-----id = 9
Process finished with exit code 0
出處:http://lavasoft.blog.51cto.com/62575/238643