Jdbc中使用Statement和PreparedStatement预编译实现模拟用户登录功能

一、Statement

public class StatementLogin {
    public static void main(String[] args) throws Exception {
        //(1)键盘输入事件,收集账号和密码信息
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入你的账号:");
        String account = scanner.nextLine();
        System.out.println("请输入你的密码:");
        String password = scanner.nextLine();

        //(2)注册驱动
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        // (3)建立连接
        Connection connection=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc1","root","123456");
        Properties info = new Properties();
        info.put("user","root");
        info.put("password","root");

        //(4)创建statement
        //statement可以发送sql语句到数据库,并且获取返回结果
        Statement statement = connection.createStatement();

        //(5)发送sql语句,并获得返回结果(1.编写sql语句 2.发送sql语句)

        String sql="select * from t_user where account='"+account+"' and PASSWORD = '"+password+"';";
        ResultSet resultSet = statement.executeQuery(sql);

        //移动一次光标,只要有数据,就代表登录成功
        if(resultSet.next()){
            System.out.println("登录成功");
        }else{
            System.out.println("登录失败");
        }

        //(7)关闭资源
        resultSet.close();
        statement.close();
        connection.close();
    }
}

二、PreparedStatement预编译

public class PrepareStatementLogin {
    public static void main(String[] args) throws Exception {
        //1.(1)收集用户信息
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入你的账号:");
        String account = scanner.nextLine();
        System.out.println("请输入你的密码:");
        String password = scanner.nextLine();

        //2.ps的数据库流程
        //(1)注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //(2)获取连接
        Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc1", "root", "123456");
        //3.编写sql语句结果
        String sql="select * from t_user where account=?and password=?;";

        //4.创建预编译statement并且设置sql语句结果
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        //5.发送sql语句,并获取返回结果
        ResultSet resultSet = preparedStatement.executeQuery();

        //6.结果解析
        if(resultSet.next()){
            System.out.println("登陆成功");
        }else{
            System.out.println("登录失败");
        }
        //7.关闭资源
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
}

总结:

Statement不能预防注入攻击

PrepareedStatement预编译可以防止注入攻击

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值