• 2022-08-19 Mysql--preparedStatement(预编译)


    我们之前用的Statement对象向数据库发送要执行的语句,但是Statement有很多的不足

    1.大量的字符串拼接,代码可读性降低。

    2.sql注入:

    SQL注入有一个BUG:

            就是通过字符串的拼接,可以得到一个恒等的sql语句,可以跳过某些判断:

            ( "b' or '1' = '1" )--------这个语句返回值一定是true,所以可以通过任何的验证

    例如:

    这样无论用户名是什么都可以登陆成功。

    1. public static void main(String[] args) {
    2. login("zxcvzxcvzxcv","b' or '1' = '1");
    3. }
    4. public static void login(String username,String password) {
    5. Connection conn = null;
    6. Statement stmt = null;
    7. ResultSet rs = null;
    8. try {
    9. conn = JDBCUtil.getConnection();
    10. stmt = conn.createStatement();
    11. String sql = "select * from user where username = '"
    12. + username + "' and password = '" + password + "'";
    13. System.out.println("sql:" + sql);
    14. rs = stmt.executeQuery(sql);
    15. if(rs.next()){
    16. System.out.println("登录成功,欢迎回来:" + username);
    17. }else {
    18. System.out.println("账号或密码错误!");
    19. }
    20. } catch (SQLException e) {
    21. throw new RuntimeException(e);
    22. } finally {
    23. JDBCUtil.close(conn,stmt,rs);
    24. }
    25. }

    PreparedStatement(预编译(预加载)接口)

    预编译语句PreparedStatement 是java.sql中的一个接口,它是Statement的子接口。通过Statement对象执行SQL语句时,需要将SQL语句发送给DBMS,由DBMS首先进行编译后再执行。预编译语句和Statement不同,在创建PreparedStatement 对象时就指定了SQL语句,该语句立即发送给DBMS进行编译。当该编译语句被执行时,DBMS直接运行编译后的SQL语句,而不需要像其他SQL语句那样首先将其编译。 

    使用: 

    1.通过connection获取的对象

    2.是Statement接口的子接口

    3.sql语句中可以传参。用?占位,通过setXXX方法来给?赋值

            eg:setString(索引,值);

    4.提高性能

    5.避免sql注入

    例子:

    1. public void test03() {
    2. Connection conn = null;
    3. PreparedStatement pstmt = null;
    4. ResultSet rs = null;
    5. try {
    6. conn = JDBCUtil.getConnection();
    7. String sql = "select * from user where username = ? and password = ?";
    8. pstmt = conn.prepareStatement(sql);
    9. pstmt.setString(1,"aaa");
    10. pstmt.setString(2,"b' or '1' = '1");
    11. rs = pstmt.executeQuery();
    12. if(rs.next()) {
    13. System.out.println("登录成功...");
    14. }else {
    15. System.out.println("账号或密码错误...");
    16. }
    17. }catch (SQLException e) {
    18. throw new RuntimeException(e);
    19. }finally {
    20. JDBCUtil.close(conn,pstmt,rs);
    21. }
    22. }

  • 相关阅读:
    ElasticSearch(es)使用游标读取全部数据
    Webpack 5 超详细解读(四)
    迁移学习:互信息的变分上下界
    Day17:图
    用 Flutter 轻松做个红包封面
    基于PHP的汉服文化交流平台毕业设计源码240903
    通过R语言且只用基础package来制作一个小游戏
    企业信息化的供给侧改革
    京东数据平台:2023年9月京东智能家居行业数据分析
    vue3.0自定义搜索 带历史数据
  • 原文地址:https://blog.csdn.net/weixin_49627122/article/details/126429943