标签:
PreparedStatement prepareStatement(String sql,int autoGeneratedKeys) throws SQLException
autoGeneratedKeys可以取值为Statement.RETURN_GENERATED_KEYS或Statement.NO_GENERATED_KEYS
取Statement.RETURN_GENERATED_KEYS值且使用的是INSERT语句时,可以取出新插入数据行中自动增长的列的值,例:
1 boolean autoCommit = conn.getAutoCommit(); 2 conn.setAutoCommit(false); 3 4 int rootId = -1; //rootId与第一列字段的值相同,第一列字段为自动增长 5 String sql = "insert into article values (null, ?, ?, ?, ?, now(), ?)"; 6 PreparedStatement pstmt = DB.createPstmt(conn, sql, Statement.RETURN_GENERATED_KEYS); 7 pstmt.setInt(1, 0); 8 pstmt.setInt(2, rootId); 9 pstmt.setString(3, request.getParameter("title")); 10 pstmt.setString(4, request.getParameter("cont")); 11 pstmt.setInt(5, 0); 12 pstmt.executeUpdate(); 13 14 ResultSet rsKey = pstmt.getGeneratedKeys(); 15 rsKey.next(); 16 rootId = rsKey.getInt(1); //取出第一列字段的值 17 Statement stmt = DB.createStmt(conn); 18 stmt.executeUpdate("update article set rootId = " + rootId + " where id = " + rootId); //更新 19 20 conn.commit(); //事务的原子性 21 conn.setAutoCommit(autoCommit); //恢复现场
适用场合:
当插入数据库中的某一字段column与某一自动增长的列相同时,先对column赋值为-1,使用该重载方法取出自动增长的列的字段值,然后执行update语句对column字段进行更新。
关于prepareStatement(String sql,int autoGeneratedKeys)的记录
标签:
原文地址:http://www.cnblogs.com/kkkkkk/p/5400253.html