PreparedStatement 获取自动生成键

 

使用可以获取自动生成键方法 Statement.RETURN_GENERATED_KEYS表示返回生成键

PreparedStatement pstmt = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);

//获取生成键的结果集

ResultSet rls = pstmt.getGeneratedKeys();

getGeneratedKeys()方法继承Statement的。                          


 Connection conn = DB.getConnection();

//获取Connection自动提交的boolean值

boolean autoCom = conn.getAutoCommit();

//将自动提交设为false

conn.setAutoCommit(false);


String title = request.getParameter("title");

int rootid = -1;

String sql = "insert into article                                                 values(null,?,?,?,?,now(),?)";

//使用可以获取自动生成键方法                                 Statement.RETURN_GENERATED_KEYS表示返回生成键

PreparedStatement pstmt = conn.prepareStatement(sql,

Statement.RETURN_GENERATED_KEYS);

pstmt.setInt(1, 0);

pstmt.setInt(2, rootid);

pstmt.setString(3, title);

pstmt.setString(4, request.getParameter("cont"));

pstmt.setInt(5, 0);

pstmt.executeUpdate();

//获取生成键的结果集

ResultSet rls = pstmt.getGeneratedKeys();

rls.next();

//根据位置得到第一个自动生成键的值

rootid = rls.getInt(1);

String strsql = "update article set rootid=" + rootid

+ " where id=" + rootid;

DB.updateDB(conn,strsql);


conn.commit();

conn.setAutoCommit(autoCom);

DB.close(pstmt);

DB.close(conn);