ORACLE中的事务管理


因为工作需求,需要向ORACLE数据插入大量的数据,进而选择了开启事务的手动管理,进行大量的数据插入,然而在此就遇到了一个坑,以前经开启mysql的事务管理进行插入数据,照搬mysql的方法有点行不通,每次插入数据只有299条能插入进去,一开始以为代码有问题,仔细检查发现代码没有问题,从网上查找原因,使用以下方法能够在JDBC中开启ORACLE事务管理,进行批量的插入数据。亲测可用:

//向***插入组织数据
    public void insertZZ(JSONArray ja) throws SQLException {
        //连接中间库
        String user = "****";
        String password = "*****";
        String url = "jdbc:oracle:thin:@ip:port/SID";
        String driver = "oracle.jdbc.driver.OracleDriver";
        Connection con = null; //一个封装了TCP长连接 的 数据库长连接对象
//        Statement stmt = null; //一个封装和管理SQL语句的java对象

        PreparedStatement preparedStatement = null;

        //插入数据
        try {
            Class.forName(driver);
            con = DriverManager.getConnection(url, user, password);

            //将事务模式设置为手动提交事务:
//            con.setAutoCommit(false);
            //设置事务的隔离级别。
//            con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);

            //运行插入操作
            int j = 2;
            String sql = "INSERT INTO IUFO_UNIT_INFO(DR,LEVEL_CODE,TS,UNIT_CODE,UNIT_ID,UNIT_NAME,UNIT_TYPE) \n" +
                    "values(?,?,?,?,?,?,?)";
            preparedStatement = con.prepareStatement(sql);
            for (int i = 0; i < ja.size(); i++) {
          con.setAutoCommit(false)//开启事务手动提交 JSONObject jo
= ja.getJSONObject(i); String dr = (String) jo.get("dr"); String level_code = (String) jo.get("level_code"); String ts = (String) jo.get("ts"); String unit_code = (String) jo.get("code"); String unit_id = (String) jo.get("unit_id"); String unit_name = (String) jo.get("name"); String unit_type = (String) jo.get("unit_type"); // String sql = "INSERT INTO IUFO_UNIT_INFO(DR,LEVEL_CODE,TS,UNIT_CODE,UNIT_ID,UNIT_NAME,UNIT_TYPE) \n" + // "values('"+dr+"','"+level_code+"','"+ts+"','"+unit_code+"','"+unit_id+"','"+unit_name+"','"+unit_type+"')"; preparedStatement.setString(1,dr); preparedStatement.setString(2,level_code); preparedStatement.setString(3,ts); preparedStatement.setString(4,unit_code); preparedStatement.setString(5,unit_id); preparedStatement.setString(6,unit_name); preparedStatement.setString(7,unit_type); preparedStatement.addBatch(); // int resultSet = preparedStatement.executeUpdate(); // System.out.println(j); } preparedStatement.executeBatch(); //提交事务 con.commit(); } catch (Exception e) { // 若事务发生异常,回滚事务 con.rollback(); }finally {
      //开启事务自动提交 con.setAutoCommit(
true); try { if (preparedStatement != null) { preparedStatement.close(); } if (con != null) { con.close(); } } catch (SQLException e) { e.printStackTrace(); } } }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM