package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Demo05 {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;//用Statement是因为prepareStatement需要预编译 占用一定的空间 如果数据量很大 可能会碰到磁盘空间不足,
ResultSet rs = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/jdbcTest?serverTimezone" +
"=UTC&characterEncoding=utf-8&useSSL=false","root","root");
conn.setAutoCommit(false);//想用批处理 一定要把自动提交关闭
long start = System.currentTimeMillis();
stmt = conn.createStatement();
for (int i = 0; i < 20000; i++) {
stmt.addBatch("insert into to_user (username, pwd, regTime) values('john" + i+"',666666,now())");
}
stmt.executeBatch();
conn.commit();//提交事务
long end = System.currentTimeMillis();
System.out.println("插入两万条数据耗时" + (end - start) + "ms");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
//一定记住关闭数据库资源 顺序 resultset --->statment ----->connection 这三个try catch块要分开写
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}