JDBC详细操作
- 灵活指定SQL语句中的变量
PreparedStatement - 对存储过程进行调用
CallableStatement - 运用事物处理
Transaction - 批处理
Batch
对于大量批处理,使用Statement,因为PreparedStatement的预编译空间有限,当数据量特别大时,会发生异常
package com.first.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class demo06 {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc","root","root");
conn.setAutoCommit(false);
long start = System.currentTimeMillis();
stmt = conn.createStatement();
for(int i=0;i<20000;i++){
stmt.addBatch("insert into t_user (username,pwd,regTime) values ('红"+i+"',123,now())");
}
stmt.executeBatch();
conn.commit();
long end = System.currentTimeMillis();
System.out.println("插入20000条数据,耗时(毫秒):"+(end-start));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if(rs!=null){
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(stmt!=null){
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}