1、PreparedStatement
1.1、PreparedStatement 和 Statement
代码的可读性和可维护性. Statement的sql拼接是个难题。
PreparedStatement 可以防止 SQL 注入
PreparedStatement 可以处理Blob类型的数据
PreparedStatement 能最大可能提高性能:(Oracle和PostgreSQL8是这样,但是对于MySQL不一定比Statement高)
DBServer(数据库管理工具)会对预编译语句提供性能优化。因为预编译语句有可能被重复调用,所以语句在被DBServer的编译器编译后的执行代码被缓存下来,那么下次调用时只要是相同的预编译语句就不需要编译,只要将参数直接传入编译过的语句执行代码中就会得到执行。
1.2、批处理
当需要成批插入或者更新记录时。可以采用Java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处理。通常情况下比单独提交处理更有效率。
JDBC的批量处理语句包括下面两个方法:
●addBatch():添加需要批量处理的SQL语句或参数
●executeBatch():执行批量处理语句;
通常我们会遇到两种批量执行SQL语句的情况:
●多条SQL语句的批量处理;
●一个SQL语句的批量传参;
注意:
JDBC连接MySQL时,如果要使用批处理功能,请再url中加参数?rewriteBatchedStatements=true
PreparedStatement作批处理插入时使用values(使用value没有效果)
批处理
package com.bdit;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
// 批处理,批处理比较快
public class JavaBacth {
public static void main(String[] args) {
//noBacth();
useBacth();
}
private static String url;
private static String user;
private static String pass;
private static String driver;
static{
url="jdbc:mysql://localhost:3306/test3?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8";
user="root";
pass="123456";
driver="com.mysql.cj.jdbc.Driver";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//没有批处理 耗时:3547
public static void noBacth(){
Connection conn=null;
PreparedStatement state=null;
String sql="insert into asd(name,money)value(?,?)";
try {
conn= DriverManager.getConnection(url,user,pass);
state=conn.prepareStatement(sql);
long start=System.currentTimeMillis();
for(int i=0;i<1000;i++){
state.setString(1,"小明");
state.setInt(2,i);
state.executeUpdate();
}
long end=System.currentTimeMillis();
System.out.println("耗时:"+(end-start));
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
if(state!=null){
try {
state.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
//批处理 耗时:3453
public static void useBacth(){
Connection conn=null;
PreparedStatement state=null;
String sql="insert into asd2(name,money)value(?,?)";
try {
conn= DriverManager.getConnection(url,user,pass);
state=conn.prepareStatement(sql);
long start=System.currentTimeMillis();
for(int i=0;i<1000;i++){
state.setString(1,"小明");
state.setInt(2,i);
state.addBatch();// 批处理
}
state.executeBatch();
long end=System.currentTimeMillis();
System.out.println("批处理耗时:"+(end-start));
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
if