String sql = "insert into article values (null, 0, ?, ?, ?, now(), 0)";
PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
conn.setAutoCommit(false);
pstmt.setInt(1, -1);
pstmt.setString(2, title);
pstmt.setString(3, content);
pstmt.executeUpdate();
ResultSet rsKey = pstmt.getGeneratedKeys();
rsKey.next();
int key = rsKey.getInt(1);
rsKey.close();
stmt.executeUpdate("update article set rootid="+key+" where id="+key);
conn.commit();
conn.setAutoCommit(true);
PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
conn.setAutoCommit(false);
pstmt.setInt(1, -1);
pstmt.setString(2, title);
pstmt.setString(3, content);
pstmt.executeUpdate();
ResultSet rsKey = pstmt.getGeneratedKeys();
rsKey.next();
int key = rsKey.getInt(1);
rsKey.close();
stmt.executeUpdate("update article set rootid="+key+" where id="+key);
conn.commit();
conn.setAutoCommit(true);
本文介绍了一种使用PreparedStatement在数据库中插入文章的方法,并展示了如何设置自动提交、获取生成的主键及提交事务。
1020

被折叠的 条评论
为什么被折叠?



