create table numbers
(
id int auto_increment primary key,
num int not null,
type varchar(2)
);
我使用的是mySql,已经把id设置为自动增长
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
/**
*使用PreparedStatement批处理数据
*将2~1000之间的数字插入数据库,并记录数字的类型(质数还是合数)
*
*/
public class TestNum {
public static void main(String[] args) throws Exception {
int num=1000;
long startTime=System.currentTimeMillis();
// insertNum1(num);// 使用Statement插入数字
// System.out.println("使用statement耗时:"+(endTime-startTime));
insertNum2(num);// 使用PreparedStatement插入数字
long endTime=System.currentTimeMillis();
System.out.println("使用PreparedStatement耗时:"+(endTime-startTime));
}
/**
* 使用PreparedStatement插入数字,批处理
* @throws Exception
*/
private static void insertNum2(int num) throws Exception {
Connection conn = JDBCUtils.getConnection();
String sql="insert into numbers values(null,?,?)";
PreparedStatement state=conn.prepareStatement(sql);
conn.setAutoCommit(false);//关闭自动提交
for(int i=2;i<=num;i++) {
//绑定参数
JDBCUtils.bind(state,i,getType(i));
//加入批处理
state.addBatch();
}
//统一执行批处理
state.executeBatch();
conn.commit();
JDBCUtils.relese(state, conn);
}
/**
* 使用Statement插入数字,并且只开关一次连接
* @throws Exception
*
*/
private static void insertNum1(int num) throws Exception {
Connection conn=JDBCUtils.getConnection();
Statement state=conn.createStatement();
for(int i=2;i<=num;i++) {
String sql="insert into numbers values(null,"+i+",'"+getType(i)+"')";
state.executeUpdate(sql);
}
JDBCUtils.relese(state, conn);
}
/**
* 判断数字类型
* @return
*/
private static String getType(int num) {
if(num<4) {
return "ZS";
}
for(int i=2;i<Math.sqrt(num);i++) {
if(num % i==0) {
return "HS";
}
}
return "ZS";
}
}
在测试PreparedStatement时,就只是需要绑定两个参数了,将id那个设置为null,运行时出现异常,这是为什么呢?
