Implement SQL statement batch processing in java
Statement implements batch processing:
Advantage: it can process multiple SQL statements with different structures
Disadvantage: preprocessing is not supported and execution efficiency is poor. For the same SQL statement with different parameters, you need to call addBatch () multiple times ()
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 database: 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')" contains invalid stat.exe cuteBatch ();} catch (Exception e) {e. printStackTrace ();} finally {DBUtil. close (conn, stat, null );}}}
PreparedStatement implements batch processing:
Advantage: It can be preprocessed and execution efficiency is high. It is easy to execute the same SQL statement with different parameters.
Disadvantage: only the same SQL statement with different batch processing parameters can be used.
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);}}}
Zookeeper