JDBC:获取数据库的自动主键

来源:互联网 发布:淘宝摄影兼职 编辑:程序博客网 时间:2024/05/19 13:30

对于像MySQL和SQL Server这种主键自动增长的可以通过PreparedStatement获取插入行的主键。

Connection conn = JdbcUtil.getConnection();

String sql = "insert intouser(name,password,email,birthday)

  values('abc','123','abc@sina.com','1978-08-08')";

PreparedStatement st = conn.

  prepareStatement(sql,Statement.RETURN_GENERATED_KEYS );

st.executeUpdate();

ResultSet rs =st.getGeneratedKeys(); //得到插入行的主键

if(rs.next())

  System.out.println(rs.getObject(1));

0 0
原创粉丝点击