工具类代码
public class JDBCUtil {
private static String driverClassName;
private static String url;
private static String userName;
private static String password;
static{
//jdbc.properties配置文件放在类路径下
InputStream in=JDBCUtil.class.getClassLoader().getSystemResourceAsStream("jdbc.properties");
Properties prop= new Properties();
try {
prop.load(in);
driverClassName=(String) prop.get("driverClassName");
url=prop.getProperty("url");
userName=prop.getProperty("username");
password=prop.getProperty("password");
Class.forName(driverClassName);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException{
Connection conn=DriverManager.getConnection(url, userName, password);
return conn;
}
public static void release(Connection conn,Statement stmt,ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs=null;
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt=null;
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn=null;
}
}
}
批处理代码:
public class JdbcDemo1 {
public static void main(String[] args) throws FileNotFoundException {
test2();
}
public static void test1(){
//利用PreparedStatement批量发送处理语句:只能执行一条sql语句
Connection conn=null;
PreparedStatement stmt=null;
ResultSet rs=null;
try {
conn=JDBCUtil.getConnection();
String sql="insert into batchtest (id,name) values(?,?)";
stmt=conn.prepareStatement(sql);
for(int i=0;i<10000000;i++){
stmt.setInt(1, i);
stmt.setString(2, "a"+i);
stmt.addBatch();
if(i%1000==0){
//可以有效的防止内存溢出
stmt.executeBatch();
stmt.clearBatch();
}
}
stmt.executeBatch();//执行尾数
} catch (SQLException e) {
e.printStackTrace();
}finally{
JDBCUtil.release(conn, stmt, rs);
}
}
public static void test2(){
//利用Statement批量发送处理语句:多条
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
try {
conn=JDBCUtil.getConnection();
stmt=conn.createStatement();
String sql1="insert into batchtest (id,name) values(1,'a')";
String sql2="insert into batchtest (id,name) values(2,'w')";
String sql3="delete from batchtest where id=1";
stmt.addBatch(sql1);
stmt.addBatch(sql2);
stmt.addBatch(sql3);
stmt.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
}finally{
JDBCUtil.release(conn, stmt, rs);
}
}
}