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

牧云@^-^@ 提交于 2019-11-26 13:45:43
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);
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!