一、編寫測試案例向MySQL數(shù)據(jù)庫中插入百萬條數(shù)據(jù)。測試數(shù)據(jù)表建表腳本如下:use db_xk;
drop table if exists tb_test2; create table tb_test2 ( id int primary key auto_increment, subject varchar(50) not null, description varchar(200) not null, teacher_id int(10) zerofill not null, student_id int(10) zerofill default null, state boolean not null default false );state boolean not null default false ); |
測試案例源碼如下:
package test; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import util.DBUtil; public class TestDataBase2 { public static void main(String[] args) { Connection conn = DBUtil.getConnection(); String sql = "insert into tb_test2(subject, description, teacher_id, student_id) values (?,?,?,?)"; try { PreparedStatement prep = conn.prepareStatement(sql); // 將連接的自動提交關(guān)閉,數(shù)據(jù)在傳送到數(shù)據(jù)庫的過程中相當(dāng)耗時(shí) conn.setAutoCommit(false); long start = System.currentTimeMillis(); for (int i = 0; i < 10; i++) { long start2 = System.currentTimeMillis(); // 一次性執(zhí)行插入10萬條數(shù)據(jù) for (int j = 0; j < 100000; j++) { prep.setString(1, "test2"); prep.setString(2, "test3"); prep.setInt(3, 1234562); prep.setInt(4, 12354545); // 將預(yù)處理添加到批中 prep.addBatch(); } // 預(yù)處理批量執(zhí)行 prep.executeBatch(); prep.clearBatch(); conn.commit(); long end2 = System.currentTimeMillis(); // 批量執(zhí)行一次批量打印執(zhí)行依次的時(shí)間 System.out.print("inner"+i+": "); System.out.println(end2 - start2); } long end = System.currentTimeMillis(); System.out.print("total: "); System.out.println(end - start); } catch (SQLException e) { e.printStackTrace(); } finally { DBUtil.close(conn); } } } |