关于prepareStatement(String sql,int autoGeneratedKeys)的记录

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字段进行更新。

转载于:https://www.cnblogs.com/kkkkkk/p/5400253.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值