Package COM.ATGUIGU.JDBC;
Import java.sql.Connection;
Import Java.sql.Date;
Import java.sql.PreparedStatement;
Import java.sql.Statement;
Import Org.junit.Test;
public class Jdbctest {
@Test
public void Testbatch () {
Connection Connection=null;
PreparedStatement Preparedstatement=null;
try{
Connection=jdbctools.getconnection ();
Jdbctools.begintx (connection);
String sql= "INSERT into customers values (?,?,?)";
Preparedstatement=connection.preparestatement (SQL);
Long Begintime=system.currenttimemillis ();
for (int i=0;i<100000;i++) {
Preparedstatement.setint (1,i+100001);
Preparedstatement.setstring (2, "");
Preparedstatement.setdate (3, New Date (New Java.util.Date (). GetTime ()));
Preparedstatement.executeupdate ();
Accumulate SQL
Preparedstatement.addbatch ();
Once accumulated to a certain extent, the unified execution once, and emptied the previously saved SQL
if ((i+1)%300==0) {
Preparedstatement.executebatch ();
Preparedstatement.clearbatch ();
}
}
If the total number of bars is not an integer multiple of the batch value, you will need to perform an additional
if ((100000%300)!=0) {
Preparedstatement.executebatch ();
Preparedstatement.clearbatch ();
}
Long Stoptime=system.currenttimemillis ();
Jdbctools.commit (connection);
System.out.println (Begintime-stoptime);
}catch (Exception e) {
E.printstacktrace ();
Jdbctools.rollback (connection);
}finally{
Jdbctools.release (NULL, PreparedStatement, connection);
}
}
@Test
public void Testbatchwithpreparedstatement () {
Connection Connection=null;
PreparedStatement Preparedstatement=null;
try{
Connection=jdbctools.getconnection ();
Jdbctools.begintx (connection);
String sql= "INSERT into customers values (?,?,?)";
Preparedstatement=connection.preparestatement (SQL);
Long Begintime=system.currenttimemillis ();
for (int i=0;i<100000;i++) {
Preparedstatement.setint (1,i+100001);
Preparedstatement.setstring (2, "");
Preparedstatement.setdate (3, New Date (New Java.util.Date (). GetTime ()));
Preparedstatement.executeupdate ();
}
Long Stoptime=system.currenttimemillis ();
Jdbctools.commit (connection);
System.out.println (Begintime-stoptime);
}catch (Exception e) {
E.printstacktrace ();
Jdbctools.rollback (connection);
}finally{
Jdbctools.release (NULL, PreparedStatement, connection);
}
}
}
Batch adding data using batch