使用 PreparedStatement.RETURN_GENERATED_KEYS 获取刚刚插入语句的ID值
使用 PreparedStatement.RETURN_GENERATED_KEYS 可以获取刚刚插入自增ID值
下面这段代码摘自 hibernate3(版本为 hibernate-distribution-3.3.1.GA)的 AbstractBatcher (在 org.hibernate.jdbc 包中)类中
private PreparedStatement getPreparedStatement(
final Connection conn,
String sql,
boolean scrollable,
final boolean useGetGeneratedKeys,
final String[] namedGeneratedKeys,
final ScrollMode scrollMode,
final boolean callable) throws SQLException {
//省略...
//useGetGeneratedKeys 表示是否是自增字段
else if ( useGetGeneratedKeys ) {
result = conn.prepareStatement( sql, PreparedStatement.RETURN_GENERATED_KEYS );
}
//省略...
return result;
}
the jdbc example:
package com.laoyangx.jdbc.chapter0;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestPreparedStatement {
/**
* @param args
* 使用PreparedStatement.RETURN_GENERATED_KEYS 获取刚刚插入语句的ID值
*/
public static void main(String[] args) {
System.err.println("Adding new column in table example!");
Connection conn=null;
PreparedStatement ps=null;
String sql="insert into customer(customer_name) values(?)";
ResultSet rs=null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/hibernate","root","123456");
ps = conn.prepareStatement( sql, PreparedStatement.RETURN_GENERATED_KEYS );
ps.setString(1, "jdbc1");
ps.executeUpdate();
rs=ps.getGeneratedKeys();
if ( !rs.next() ) {
System.err.println("wrong ...");
}
final int CUSTOMER_ID_COLUMN_INDEX=1;
System.err.println(rs.getInt( CUSTOMER_ID_COLUMN_INDEX )); //输出刚插入数据返回的Id号
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
finally{
try {
if(rs!=null) rs.close();
if(ps!=null) ps.close();
if(conn!=null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
运行程序之前,customer表中的数据如下图所示:

运行程序之后,customer表中的数据如下图所示:

控制台的输出如下图所示:


浙公网安备 33010602011771号