PrepareStatement:执行SQL对象
1.SQL注入问题:在拼接SQL时,有一些SQL的特殊关键字参与字符串的拼接。会造成安全性问题
- 输入用户名随便,输入密码:a’ or ‘a’ = 'a
- 解决SQL注入问题:使用PreparedStatement对象来解决
- 预编译的SQL:参数使用?作为占位符
2.步骤:
-
导入驱动jar包
-
注册驱动
-
获取连接
-
定义SQL
注意:SQL使用 ? 作为占位符。如:
String sql = "select * from user where username = ? and password = ?";
- 获取执行SQL语句的对象
PreparedStatement Connection.prepareStatement(String sql)
pstmt = conn.prepareStatement(sql);
- 给 ? 赋值:
方法:setXxx(参数1,参数2),如:
pstmt.setString(1,username);
pstmt.setString(2,password);
参数1:?的位置编号,从1开始
参数2:?的值
- 执行SQL,接受返回结果,不需要传递sql语句:
rs = pstmt.executeQuery();
-
处理结果
-
释放资源
完整版代码:
import util.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class JDBCsafe {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名:");
String username = sc.nextLine();
System.out.println("请输入密码:");
String password = sc.nextLine();
boolean logincheck = new JDBCsafe().login2(username, password);
if (logincheck)
System.out.println("登录成功");
else
System.out.println("登录失败");
}
public boolean login2(String username,String password){
Connection conn = null;
ResultSet rs = null;
PreparedStatement pstmt = null;
if (username == null || password == null){
return false;
}
try {
conn = JDBCUtils.getConnection();
// 定义SQL
String sql = "select * from user where username = ? and password = ?";
// 获取SQL对象
pstmt = conn.prepareStatement(sql);
// 给?赋值
pstmt.setString(1,username);
pstmt.setString(2,password);
// 执行SQL
rs = pstmt.executeQuery();
return rs.next();
} catch (SQLException e) {
e.printStackTrace();
}finally {
//释放资源
JDBCUtils.close(pstmt, conn, rs);
}
return false;
}
}
MySQL数据库表(user):
执行结果:
1.成功登录:
2.防止SQL注入的结果: