PreparesStatement比Statement的优势
优势1:代码可读性/维护性更高。
优势2:PreparedStatement的执行性能更高。
PreparedStatement是预编译语句对象,怎么理解。
1.安全性检查
2.SQL语法分析
3.语法编译:编译成二进制
4.选择并执行一个计划
在有的数据库服务器中:会把每次执行的SQL给缓存下来,若下次的SQL已经在缓存中,则直接执行第四部。
//事实证明mysql不会把每次执行的缓存下来,性能并没有增加!
//使用Statement插入1000条数据
//Innodb:35016
//Myisam:611
@Test
public void test1() throws Exception {
Long begin = System.currentTimeMillis();
Connection conn = JdbcUtil.INSTANCE.getConn();
Statement st = conn.createStatement();
for (int i = 1; i < 1001; i++) {
String sql = "insert into t_user (username,email) values ('西门','哈哈')";
st.executeUpdate(sql );
}
JdbcUtil.INSTANCE.close(conn, st, null);
System.out.println(System.currentTimeMillis() - begin);
}
//使用PreparedStatement插入1000条数据
//Innodb:30008
//Myisam:658
@Test
public void test2() throws Exception {
Long begin = System.currentTimeMillis();
Connection conn = JdbcUtil.INSTANCE.getConn();
String sql = "insert into t_user (username,email) values (?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
for (int i = 1; i < 1001; i++) {
ps.setString(1, "");
ps.setString(2, "");
ps.executeUpdate();
}
JdbcUtil.INSTANCE.close(conn, ps, null);
System.out.println(System.currentTimeMillis() - begin);
}
优势3:安全性更高,防止SQL注入问题。
登录设计的时候,Statement不如PreparedStatement安全!
//把' or 1 = 1 or '带入账号中不正确
@Test
public void tastPreparedStatementStatementLogin() throws Exception {
Connection conn = JdbcUtil.INSTANCE.getConn();
String sql = "SELECT * FROM t_user where username = ? and password = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, "' or 1 = 1 or '");
ps.setString(2, "1");
ResultSet rs = ps.executeQuery();
if(rs.next()){
System.out.println("ok啦....");
}else{
System.out.println("nook啦....");
}
JdbcUtil.INSTANCE.close(conn, ps, rs);
}
//把' or 1 = 1 or '带入则正确就是因为它把username = '' or 1 = 1 or ''分开看前面false后面ture
@Test
public void tastStatementLogin() throws Exception {
Connection conn = JdbcUtil.INSTANCE.getConn();
Statement st = conn.createStatement();
// String sql = "SELECT * FROM t_user where username = 'admin' and password = '1'";
String sql = "SELECT * FROM t_user where username = '' or 1 = 1 or '' and password = '1'";
ResultSet rs = st.executeQuery(sql);
if(rs.next()){
System.out.println("ok啦....");
}else{
System.out.println("nook啦....");
}
JdbcUtil.INSTANCE.close(conn, st, rs);
}