Statement implement batch processing:
Pros: Ability to handle multiple SQL statements with different structures
Disadvantage: Can not be preprocessed, execution efficiency is poor. Multiple calls to Addbatch () for the same SQL statement with different parameters
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 (i d 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 ())"); s Tat.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 Implement batch processing:
Advantages: Ability to pre-process, high execution efficiency; the same SQL statement with different parameters is easy to perform
Cons: Only the same SQL statement with different batch parameters
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 ();p s = conn.preparestatement ("INSERT into Mybatch value (null,?)"); for (int i = 0; i < i++) {ps.setstring (1, "name" + i);p s.addbatch ();} Ps.executebatch ();} catch (Exception e) {e.printstacktrace ();} finally {dbutil.close (conn, PS, NULL);}}}
Java implementation SQL statement batch processing