欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JdbcBaseReview系列之JdbcPrepare的前言

程序员文章站 2022-06-02 17:03:53
...

在分享PreparedStatement之前我们先做一个小的测试demo来看一下PreparedStatement它的好处
写一个简易的用户登录的小demo来试一下 用户名和密码是在之前写好的Stu这个类里面的数据 我就直接拿来用了

//SQL注入
public class jdbc {

    private static String driverClass = "com.mysql.jdbc.Driver";
    private static  String url = "jdbc:mysql://localhost:3306/jdbc";
    private  static  String uesr = "root";
    private  static String password = "111111";
    private  static Connection connection = null;
    private  static Statement statement = null;
    private static  ResultSet resultSet = null;

    @Test
    public void t1() throws ClassNotFoundException, SQLException {
        try {

            Class.forName(driverClass);
            connection = DriverManager.getConnection(url, uesr, password);
            statement = connection.createStatement();
            resultSet =  statement.executeQuery("SELECT *FROM stu");
            while (resultSet.next()){
                System.out.println(resultSet.getInt("age") + resultSet.getString("name") + resultSet.getInt("id"));
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
        }

    }


    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Class.forName(driverClass);
        connection = DriverManager.getConnection(url, uesr, password);
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名");
        String name = scanner.nextLine();
        System.out.println("请输入密码");
        String pass = scanner.nextLine();
//在没学习Prepare之前用的是statement这个类来实现的 但是如果输入的用户名和密码带有''分号, or这样的字眼就会有任何一个成功就会登录成功 但是我们知道登录要用户和密码都要对才可以登录成功 所以之后学习了PrepareStatement之后就会很好的解决这一问题
//        statement = connection.createStatement();
//
//         resultSet = statement.executeQuery("SELECT *FROM stu WHERE name='"+name+"'  AND age="+pass+" ;");
        PreparedStatement stmt = connection.prepareStatement("SELECT *FROM stu WHERE name=? AND age=? ");
        stmt.setString(1,name);
        stmt.setString(1, pass);
         resultSet = stmt.executeQuery();
//字符串拼接打印后的样子
        String sql = "select * from stu WHERE name='"+name+"' AND age="+pass+";";
        System.out.println(sql);
       if (jdbc.resultSet.next()){
           System.out.println("登录成功");
       }else {
           System.out.println("登录失败");
       }



    }

}
相关标签: 数据 class