PreparedStatement是Statement的子接口,它的实例对象可以通过调用Connection.preparedStatement(sql)方法获得,相对于Statement对象而言:
- PreparedStatement可以避免SQL注入的问题
- Statement会使数据库频繁编译SQL,可能造成数据库缓冲区溢出。PreparedStatement可以对SQL进行预编译,从而提高数据库的执行效率。
- 并且PreparedStatement对于SQL中的参数,允许使用占位符的形式进行替换,简化SQL语句的编写。
package com.imooc.jdbc.dome1;
import java.sql.ResultSet;
import com.imooc.jdbc.utils.JDBCUtils;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
public class JDBCDemo4 {
/**
* 避免SQL注入漏洞的方法
*/
public static boolean login(String username, String password) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rSet = null;
boolean flag = false;
try {
conn = JDBCUtils.getConnection();
String sql = "select * from user where username = ? and password = ?";
//预处理SQL
pstmt = (PreparedStatement)conn.prepareStatement(sql);
//设置参数
pstmt.setString(1, username);
pstmt.setString(2, password);
//执行SQL
rSet = pstmt.executeQuery();
if(rSet.next()) {
flag = true;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
JDBCUtils.release(pstmt, conn, rSet);
}
return flag;
}
}