PreparedStatement.RETURN_GENERATED_KEYS可以获取刚刚插入数据的id
当使用自增字段时,可以通过这种凡是获取ID值
[quote]
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号
[/quote]
当使用自增字段时,可以通过这种凡是获取ID值
[quote]
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号
[/quote]