数据库的简单批处理(增、删、改)

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import org.junit.Test;

import java.sql.PreparedStatement;
import com.qf.b_utils.DBUtils;

/**
 * @author Zhouzilong
 * @date 2019年8月8日
 */
public class BatchTest {
    /**
     * 多条不同语句
     */
    @Test
    public void batchTest1() {
        Connection conn = null;
        Statement st = null;

        try {
            conn = DBUtils.getConnection();
            st = conn.createStatement();
            st.addBatch("insert into t_user(name,password) values('ooo','123456')");
            st.addBatch("update t_user set name = 'oo' where name = 'ooo'");
            st.executeBatch();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            DBUtils.closeAll(st, conn);
        }
    }

    /**
     * 100条参数不同的相同语句
     */
    @Test
    public void batchTest2() {
        Connection conn = null;
        PreparedStatement prst = null;

        try {
            conn = DBUtils.getConnection();
            prst = conn.prepareStatement("insert into t_user(name,password) values(?,?)");
            for (int i = 1; i <= 100; i++) {
                prst.setString(1, "zs" + i);
                prst.setString(2, "12" + i);
                prst.addBatch();
            }
            prst.executeBatch();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            DBUtils.closeAll(prst, conn);
        }
    }

    /**
     * 分批插入1000条参数不同的相同语句
     */
    @Test
    public void batchTest3() {
        Connection conn = null;
        PreparedStatement prst = null;

        try {
            conn = DBUtils.getConnection();
            prst = conn.prepareStatement("insert into t_user(name,password) values(?,?)");
            for (int i = 1; i <= 1000; i++) {
                prst.setString(1, "zs" + i);
                prst.setString(2, "12" + i);
                prst.addBatch();
                if (i % 100 == 0) {
                    // 每100条执行一次批处理
                    prst.executeBatch();
                    
                    // 清空缓冲区
                    prst.clearBatch();
                }
                //后两句一般要加上
                prst.executeBatch();
                prst.clearBatch();
            }
            // 插入1000条只与数据库交互一次
            prst.executeBatch();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtils.closeAll(prst, conn);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值