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

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

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

2.sql注入:

SQL注入有一个BUG:

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

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

例如:

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

    public static void main(String[] args) {
        login("zxcvzxcvzxcv","b' or '1' = '1");
    }
    public static void login(String username,String password) { 
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtil.getConnection();
            stmt = conn.createStatement();
            String sql = "select * from user where username = '"
                         + username + "' and password = '" +  password + "'";
            System.out.println("sql:" + sql);
            rs = stmt.executeQuery(sql);
            if(rs.next()){
                System.out.println("登录成功,欢迎回来:" + username);
            }else {
                System.out.println("账号或密码错误!");
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtil.close(conn,stmt,rs);
        }
    }

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注入

例子:

public void test03() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtil.getConnection();
            String sql = "select * from user where username = ? and password = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,"aaa");
            pstmt.setString(2,"b' or '1' = '1");
            rs = pstmt.executeQuery();
            if(rs.next()) {
                System.out.println("登录成功...");
            }else {
                System.out.println("账号或密码错误...");
            }
        }catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JDBCUtil.close(conn,pstmt,rs);
        }
    }

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值