zoukankan      html  css  js  c++  java
  • JDBC如何避免SQL注入

    JDBC如何避免SQL注入

    什么是SQL注入

    用户输入的数据中有SQL关键字或语法并且参与了SQL语句的编译,导致SQL语句编译后的条件含义为true,一直得到正确的结果。这种现象称为SQL注入。

    如何避免SQL注入

    由于编写的SQL语句是在用户输入数据,整合后再进行编译。所以为了避免SQL注入的问题,我们要使SQL语句在用户输入数据前就已进行编译成完整的SQL语句,再进行填充数据。

    使用PreparedStatement来避免SQL注入

    PreparedStatement继承了Statement接口,执行SQL语句的方法无异。

    PreparedStatement的作用

    • 预编译SQL语句,效率高
    • 安全,避免SQL注入
    • 可以动态的填充数据,执行多个同构的SQL语句

    参数标记

    //1.预编译SQL语句
    PreparedStatement pstmt = coonection.prepareStatement("select * from where username=? and password=?");
    
    • 注意:JDBC中的所有参数都由?符号占位,这被称为参数标记。在执行SQL语句之前,必须为每个参数提供值。

    动态参数绑定

    pstmt.setXXX(下标,值) 参数下标从1开始

    //1.预编译SQL语句
    PreparedStatement pstmt = conn.prepareStatement ("select * from user where username = ? and password = ?") ;
    //2.为参数下标赋值
    pstmt.setString (1,username);
    pstmt.setString(2,password);
    

    执行SQL语句,接受结果

    ResultSet resultSet = preparedStatement.executeQuery();
    
  • 相关阅读:
    常用英语1000句
    TXT EXPLORER
    窗体美化
    C++ Code_StatusBar
    C++ Code_Slider
    C++ Code_ScrollBar
    C++ Code_ImageList
    C++ Code_HotKey
    C++ Code_animateCtrl
    C++ CheckMenuItem
  • 原文地址:https://www.cnblogs.com/techoc/p/13625569.html
Copyright © 2011-2022 走看看