PreparedStatement类对SQL注入问题的解决

1.Satement对象每执行一条SQL语句都会先将这条SQL语句发送给数据库编译,数据库再执行。
  如果有1万条类似的SQL语句,数据库需要编译1万次,执行1万次,显然效率就低了。
  并且statement执行的是静态的sql语句
2.prepareStatement()会先将SQL语句发送给数据库预编译。PreparedStatement会引用着预编译后的结果。可以多次传入不同的参数给PreparedStatement对象并执行。
  相当于调用方法多次传入不同的参数
 
3.PreparedSatement的好处
prepareStatement()会先将SQL语句发送给数据库预编译。
PreparedStatement会引用着预编译后的结果。
可以多次传入不同的参数给PreparedStatement对象并执行。
减少SQL编译次数,提高效率。
 
安全性更高,没有SQL注入的隐患。
 
提高了程序的可读性
 
PreparedSatement使用步骤? 1.获取连接 2.先写SQL语句带?的 3.获取PreparedStatement,预编译 4.设置参数 5.执行SQL 6.关闭资源
PreparedSatement实现增删查改使用哪个方法? executeUpdate(); 执行增删改 exexuteQuery(); 执行查询
/*
*
* sql注入:数据库对用户传入的参数进行了编辑,改变了原本的sql的结构
*       预编译:在用户传入参数之前先进行编译,确定sql的结构,在传入用户的参数执行
*       1.select count(*) from user where username = ? and password = ?;
*       对于参数部分使用占位符?
*       2.编译完毕之后,确定了结构才传入参数
*       3.对于用户传入的特殊字符参数,使用转义,变成没有实际意义的字符
* 
* 预编译操作对象的获取api:
*       PreparedStatement prepareStatement(String sql) 创建一个 PreparedStatement对象,用于将参数化的SQL语句发送到数据库。
* */

1.executeQuery()方法,主要用DQL语句
public class LoginDemo {
    public static void main(String[] args) throws SQLException {
       

        Connection connection = JdbcUtil.getConnection();

        String sql = "SELECT count(*) FROM USER WHERE username = ? AND password = ? ;";
       
        //1.在用户传入参数之前先进行编译,确定sql的结构
        PreparedStatement statement = connection.prepareStatement(sql);

        //2.预编译完毕之后,再传入用户的参数
        statement.setString(1,username);
        statement.setString(2,password);

        //3.执行sql即可
        ResultSet resultSet = statement.executeQuery(); //注意:预编译时,sql不用再传,之前已经传递过了

        int count = 0;
        while (resultSet.next()) {
            count = resultSet.getInt("count(*)");
        }
        System.out.println(count >0 ? "登录成功" :" 登录失败");

        JdbcUtil.release(resultSet,statement,connection);
    }
}


2.executeUpdate()方法,主要用于DML语句(update,delete,insert)
public class CRUDDemo {
    @Test
    public void insertTest() throws SQLException {

        Connection connection = JdbcUtil.getConnection();
        //使用预编译进行数据的插入
        String sql = "INSERT  into USER  VALUES (?,?,?)";

        PreparedStatement statement = connection.prepareStatement(sql);

        statement.setInt(1,6);
        statement.setString(2,"liubei");
        statement.setString(3,"123456");

        int executeUpdate = statement.executeUpdate();
        System.out.println(executeUpdate);

        JdbcUtil.release(null,statement,connection);
    }
}

猜你喜欢

转载自blog.csdn.net/LOVE_Me__/article/details/104647217