使用PreparedStatement防止注入攻击

public class JDBCDemo2Login {
    public static void main(String[] args) throws SQLException {
        //1.获取页面数据
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String uname = sc.nextLine();
        System.out.println("请输入密码:");
        String upass = sc.nextLine();

        //2.获取数据连接对象
        Connection con = JDBCUtil.getConnect();
        //3.获取执行sql的PreparedStatement对象,并传递sql语句
        //4.定义sql语句
        String sql = "select * from users where uname = ? and upass = ?";
        PreparedStatement pstmt = con.prepareStatement(sql);

        //5.PreparedStatement对象调用方法,给sql语句中的?赋值
        pstmt.setObject(1,uname);
        pstmt.setObject(2,upass);

        //6.PreparedStatement对象执行结果,获取结果
        ResultSet rs = pstmt.executeQuery();
        //7.处理结果
        if (rs.next()){
            System.out.println("登录成功");
        }else {
            System.out.println("登录失败");
        }
        System.out.println(pstmt);
        //8.释放资源
        JDBCUtil.release(con,pstmt,rs);
    }
}

posted @ 2020-08-15 00:04  硬盘红了  阅读(152)  评论(0编辑  收藏  举报