手记

oracle数据库批处理演示

package cabby;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 批处理演示
 * @author Cabby
 *
 */
public class BatchDemo {
    public static void main(String[] args) {
        batchSql();
    }
    public static void batchSql(){
        String sql="insert into mytemp_xxx(id) values(?)";
        Connection conn=null;
        PreparedStatement stmt=null;
        try {
            conn=JDBCUtil.getConnection();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            conn.setAutoCommit(false);
            stmt=conn.prepareStatement(sql);
            for(int i=1;i<=105;i++){
                stmt.setInt(1, i);
                //把sql语句加入批处理
                stmt.addBatch();
                //每10条记录处理一次
                //避免批处理中的sql语句太多
                if(i%10==0){
                    //执行
                    stmt.executeBatch();
                    //清除
                    stmt.clearBatch();
                }
            }
            //执行最后的5条sql
            stmt.executeBatch();
            conn.commit();
        } catch (SQLException e) {
            try {
                //发生异常时回滚
                conn.rollback();
            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally{
            try {
                stmt.close();
                JDBCUtil.close(conn);
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
4人推荐
随时随地看视频
慕课网APP