標籤:style blog io os ar java for 資料 div
Statement實現批處理:
優點:能夠處理多種不同結構的sql語句
缺點:不能預先處理,執行效率較差。對於參數不同的同一條sql語句需要多次調用addBatch()
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'); */@Testpublic 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語句
package com.itheima.batch;import java.sql.Connection;import java.sql.PreparedStatement;import org.junit.Test;import com.itheima.util.DBUtil;public class PrepBatch {@Testpublic 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語句批處理