有时候,在用insert插入数据后,想获得刚插入记录的ID,可以利用JDBC的getGeneratedKeys获得INSERT插入后生成的主键ID。本例数据库为MySQL,主键ID为int类型,用auto_increment生成。
以下为主要的Java代码 :
[java]
view plain
copy
- ps = conn.prepareStatement("insert into test(name) value(?)",Statement.RETURN_GENERATED_KEYS);
- ps.setString(1, "test");
- ps.execute();
- rs = ps.getGeneratedKeys();
- int id=0;//保存生成的ID
- if (rs != null&&rs.next()) {
- id=rs.getInt(1)
- }
本例用到的主要方法为以下两个,可以查阅JDK参考文档:
1、PreparedStatement prepareStatement ( String sql, int autoGeneratedKeys) throws SQLException(在java.sql.Connection接口中)
2、ResultSet getGeneratedKeys () throws SQLException(在java.sql.PreparedStatement 接口中)
原文链接:http://blog.youkuaiyun.com/security08/article/details/4704706