• MySQL之SQL注入及解决


    SQL注入攻击的原理

    我们在密码处输入的所有内容都应该是密码的组成。

    但是现在Statement对象在执行sql语句时,将密码的一部分内容当做查询条件来执行了。

    // 将用户输入的账号密码拼接后
    SELECT * FROM user WHERE name='hehe' AND password='a'or'1'='1';
    
    • 1
    • 2

    解决

    Statement的子接口PreparedStatement

    PreparedStatement预编译执行者对象

    预编译:SQL语句在执行前就已经编译好了,执行速度更快。

    安全性更高:没有字符串拼接的SQL语句,所以避免SQL注入的问题

    代码的可读性更好,因为没有字符串拼接

    PreparedStatement使用

    SQL语句中的参数使用?作为占位符
    给?占位符赋值

    设置参数

    setXxx(参数1,参数2); Xxx代表:数据类型
    参数1:第几个? (编号从1开始)
    参数2:?的实际参数

    执行SQL语句

    int executeUpdate(); 执行insert、update、delete语句
    ResultSet executeQuery(); 执行select语句

    public static void main(String[] args) throws SQLException {
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入账号密码:");
            String name = scanner.next();
            String password = scanner.next();
    
            // 1.获取连接
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1?useSSL=false&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT","root","1234");
            // 2.编写参数化SQL(带?的SQL语句)
            String sql = "select * from account where name = ? and balance = ?";
            PreparedStatement prepareStatement = connection.prepareStatement(sql);
            // 3.给?赋值
            //数字1代表第一个?
            prepareStatement.setString(1,name);
            prepareStatement.setString(2,password);
            // 4.执行
            ResultSet resultSet = prepareStatement.executeQuery();
            if(resultSet.next()){
                System.out.println("成功");
            }else{
                System.out.println("失败");
            }
            // 5.释放资源
            resultSet.close();
            prepareStatement.close();
            connection.close();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    最后

    如果你对本文有疑问,你可以在文章下方对我留言,敬请指正,对于每个留言我都会认真查看。

  • 相关阅读:
    软件架构设计(五) 软件架构风格-微服务
    Java和Vue项目打包并进行服务器部署
    批量提取图片文件名使用Python中os.listdir( )函数时出现文件名乱序,非预想排序的解决方法
    卡塔尔世界杯在哪里可以看直播?
    istio安装文档
    Linux的学习笔记
    【笔试题】【day15】
    MySQL主从复制(读写分离)
    java学习--字符流
    中文drupal教程1. 自动加载器与Composer
  • 原文地址:https://blog.csdn.net/weixin_47543906/article/details/128001178