1、提高程序的运行速度
只要被预处理处理过得sql语句,都会提前被数据库处理存入到缓存中,减小了对数据库的压力,提高了程序的运行速度;
2、预防绝大多数的SQL注入
预处理代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestP {
public static void main(String args[]) {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:aaa", "", "");
String sql = "select sid,sname,sage from student where sage=? and sname=?";
ps=con.prepareStatement(sql);//封装sql指令
ps.setString(1, "22");//1为下标 22 为要插入的值
ps.setString(2, "小志");
rs=ps.executeQuery();//执行查询操作
while(rs.next()){
System.out.println(rs.getString("sid")+rs.getString("sname")+rs.getString("sage"));
}
String sql1 = "insert into student values(?,?,?)";
ps=con.prepareStatement(sql1);
ps.setString(1, "6");
ps.setString(2, "韩雪");
ps.setString(3, "26");
ps.executeUpdate();//执行更新操作
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
if(rs!=null){
rs.close();
}
if(ps!=null){
ps.close();
}
if(con!=null){
con.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Why预防SQL注入?
因为SQL语句在程序运行前已经进行了预编译,在程序运行时第一次操作数据库之前,SQL语句已经被数据库分析,编译和优化,对应的执行计划也会缓存下来并允许数据库已参数化的形式进行查询,当运行时动态地把参数传给PreprareStatement时,即使参数里有敏感字符如 or '1=1'也数据库会作为一个参数一个字段的属性值来处理而不会作为一个SQL指令,如此,就起到了SQL注入的作用了!