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
[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 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 ');
- */
- @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 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
[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 < ; i++) {
- Ps.setstring (1, "name" + i);
- Ps.addbatch ();
- }
- Ps.executebatch ();
- } catch (Exception e) {
- E.printstacktrace ();
- } finally {
- Dbutil.close (conn, PS, null);
- }
- }
- }
Java implementation SQL statement batch processing