取得刚插入的数据ID

来源:互联网 发布:b ab 知乎 编辑:程序博客网 时间:2024/05/01 22:02

Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost/bbs?user=root&password=root";
Connection conn = DriverManager.getConnection(url);

conn.setAutoCommit(false);  //将此连接的自动提交模式设置为手动执行状态

String sql = "insert into article values (null, 0, ?, ?, ?, now(), 0)";
PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);//当前的键生成索引可用于检索
Statement stmt = conn.createStatement();

pstmt.setInt(1, -1);
pstmt.setString(2, title);
pstmt.setString(3, cont);
pstmt.executeUpdate();

ResultSet rsKey = pstmt.getGeneratedKeys();
rsKey.next();
int key = rsKey.getInt(1);//取得刚插入的数据ID
rsKey.close();
stmt.executeUpdate("update article set rootid = " + key + " where id = " + key);

conn.commit();
conn.setAutoCommit(true);

stmt.close();
pstmt.close();
conn.close();