Java数据库操作要点

事务的处理


要点:执行每一个新的sql语句前,上一次执行sql语句的Statement(或者PreparedStatemet)必须先 close。批处理有addBatch()和addBatch(String sql) 两种方法,oracle只实现了addBatch()方法,故用oracle数据库时批处理只能写成:

               Connection conn = DBPool.getInstance().getConnection();
                 //关闭Connection的自动提交
                conn.setAutoCommit( false);
                String sql = "insert into user values(USER_SEQ.nextval,?,?)";
                PreparedStatement pstmt = conn.prepareStatement(sql);
                 for ( int i = 0; i < 3; i++) {
                        pstmt.setInt(1,i);
                        pstmt.setString(2, "name"+i);
                         //添加一条批处理语句,只能调用addBatch()方法,且语句只能是insert或update,不能是select
                        pstmt.addBatch();
                }
                pstmt.executeBatch();
                conn.commit();
                DBPool.closeStatement(pstmt);
                DBPool.closeConn(conn);



获取插入数据的主键


               Connection conn = DBPool.getInstance().getConnection();
                String sql = "insert into user values(USER_SEQ.nextval,?,?)";
                PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                pstmt.setInt(1, 1);
                pstmt.setString(2, "name");
                pstmt.executeUpdate();
                ResultSet rs = pstmt.getGeneratedKeys();
                 int id = 0;
                 if (rs.next()) {
                        id = rs.getInt( "id");
                }
                DBPool.closeStatement(pstmt);
                DBPool.closeConn(conn);





你可能感兴趣的:(java,数据库,职场,休闲,要点)