public class testGetKeyValue {
/**
* 取得数据库自动生成的主键
*/
@Test
public void testGeneratedKeys() {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs=null;
try {
conn = JDBCTools.getConnection();
String sql = "INSERT INTO customers(name,email,birth) VALUES(?,?,?)";
// 使用重载的prepareStatement方法来生产 PreparedStatement对象
ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, "AAA");
ps.setString(2, "aaa@sina.com");
ps.setDate(3, new Date(new java.util.Date().getTime()));
ps.executeUpdate();
rs=ps.getGeneratedKeys();//得到插入行的主键
if(rs.next()){
System.out.println(rs.getObject(1));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCTools.close(rs, ps, conn);
}
}
}
Java_jdbc 基础笔记之十五 数据库连接(取得数据库自动生成的主键)
最新推荐文章于 2025-06-10 13:59:12 发布