首页 > 代码库 > java实现sql语句批处理
java实现sql语句批处理
Statement实现批处理:
优点:能够处理多种不同结构的sql语句
缺点:不能预处理,执行效率较差。对于参数不同的同一条sql语句需要多次调用addBatch()
[java] view plain copy
- package com.itheima.batch;
- import java.sql.Connection;
- import java.sql.Statement;
- import org.junit.Test;
- import com.itheima.util.DBUtil;
- public class StatementBatch {
- /* mysql数据库:
- create database batch;
- use batch;
- create table mybatch(
- id int primary key auto_increment,
- name varchar(50)
- );
- insert into mybatch values (null, ‘1‘);
- insert into mybatch values (null, ‘2‘);
- insert into mybatch values (null, ‘3‘);
- insert into mybatch values (null, ‘4‘);
- */
- @Test
- public void statementBatch() {
- Connection conn = null;
- Statement stat = null;
- try{
- conn = DBUtil.getConn();
- stat = conn.createStatement();
- stat.addBatch("create database batch");
- stat.addBatch("use batch");
- stat.addBatch("create table mybatch( id int primary key auto_increment, name varchar(50) )");
- stat.addBatch("insert into mybatch values (null, ‘1‘)");
- stat.addBatch("insert into mybatch values (null, ‘2‘)");
- stat.addBatch("insert into mybatch values (null, ‘3‘)");
- stat.addBatch("insert into mybatch values (null, ‘4‘)");
- stat.executeBatch();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- DBUtil.close(conn, stat, null);
- }
- }
- }
PreparedStatement实现批处理:
优点:能够预处理,执行效率高;参数不同的同一条sql语句执行简便
缺点:只能批处理参数不同的同一条sql语句
[java] view plain copy
- package com.itheima.batch;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import org.junit.Test;
- import com.itheima.util.DBUtil;
- public class PrepBatch {
- @Test
- public void prepBatch() {
- Connection conn = null;
- PreparedStatement ps = null;
- try{
- conn = DBUtil.getConn();
- ps = conn.prepareStatement("insert into mybatch value(null, ?)");
- for(int i = 0; i < 1000; i++) {
- ps.setString(1, "name" + i);
- ps.addBatch();
- }
- ps.executeBatch();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- DBUtil.close(conn, ps, null);
- }
- }
- }
java实现sql语句批处理
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。