下面以用户登录为案例,对比使用PreparedStatement和不使用PreparedStatement的区别
先介绍下SQL注入:
SQL注入:在拼接SQL时,有一些特殊关键字参与字符串的拼接,会造成安全问题
解决SQL注入的问题:使用Preparedstatement对象来解决
预编译的SQL:参数使用?作为占位符
如:select * from user where username=? and password =?;
然后在给?进行赋值,通过setString实现
如:
pstmt.setString(1,username);//1代表第一个问号,username代表的内容
pstmt.setString(2,password);
练习
/*
需求:
通过键盘录入用户名和密码
判断用户是否登录成功
* */
public class jdbcdemo07 {
public static void main(String[] args) {
//1.键盘录入
Scanner sc=new Scanner(System.in);
System.out.println("请输入用户名");
String username = sc.next();
System.out.println("请输入密码");
String password = sc.next();
//2.调用方法
boolean flag = new jdbcdemo07().login2(username,password);
//3.判断结果,输出不同语句
if (flag){
System.out.println("登录成功");
}else{
System.out.println("密码错误");
}
}
/*
登录方法,不使用PreparedStatement登录
* */
public boolean login(String username,String password){
if (username==null||password==null){
return false;
}
Connection conn=null;
Statement stmt =null;
ResultSet rs=null;
try {
//1.获取连接
conn= jdbcutil.getConnection();
//2.定义SQL
String sql="select * from user where username='"+username+"' and password = '"+password+"'";
//3.获取执行SQL对象
stmt = conn.createStatement();
//4.执行查询
rs = stmt.executeQuery(sql);
//5.判断
return rs.next();//如果有下一行,则返回true
} catch (SQLException e) {
e.printStackTrace();
}finally {
jdbcutil.close(rs,stmt,conn);
}
return false;
}
=======================================================================
//此处为使用PreparedStatement与不使用PreparedStatement的分割线
========================================================================
/*
登录方法,使用PreparedStatement登录
* */
public boolean login2(String username,String password){
if (username==null||password==null){
return false;
}
Connection conn=null;
PreparedStatement pstmt =null;
ResultSet rs=null;
try {
//1.获取连接
conn= jdbcutil.getConnection();
//2.定义SQL
String sql = "select * from user where username = ? and password = ?";
//3.获取执行SQL对象
pstmt = conn.prepareStatement(sql);
//给?赋值
pstmt.setString(1,username);
pstmt.setString(2,password);
//4.执行查询,不需要传递SQL
rs = pstmt.executeQuery();
//5.判断
return rs.next();//如果有下一行,则返回true
} catch (SQLException e) {
e.printStackTrace();
}finally {
jdbcutil.close(rs,pstmt,conn);
}
return false;
}
}