zoukankan      html  css  js  c++  java
  • 关于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字段进行更新。

  • 相关阅读:
    codeforces 1060 B
    codeforces 1060 A
    牛客 国庆七天乐 day1 L
    BZOJ 1087: [SCOI2005]互不侵犯King
    codeforces 792CDivide by Three(两种方法:模拟、动态规划
    codeforces 797C Minimal string
    codeforces 110E Lucky Tree
    codeforces 798D
    2017福建省赛 FZU2272~2283
    Android -- Looper、Handler、MessageQueue等类之间关系的序列图
  • 原文地址:https://www.cnblogs.com/kkkkkk/p/5400253.html
Copyright © 2011-2022 走看看