JDBC---Mysql(2)

SQL注入攻击:

用户可以提交一段数据库查询代码,根据程序返回的结果,获得某些他想知道的数据,这就是所谓的SQL注入攻击,

例如:判断username='a' or 'a'='a';  true从而为真,然后查询到信息

下面是一个登录查询数据库--返回结果为true

//用的查询是where 名字and密码都对的才返回true,说明数据库中有这个用户    
        /*
     * 登录 使用username和password去查询数据 若查出结果集,说明正确!返回true 若查不出结果,说明用户名或密码错误,返回false
     */

    public boolean login(String username, String password)
            throws ClassNotFoundException, SQLException {

        /*
         * 1得到connection 2得到statement 3得到resultset 4rs.next()返回的是什么,我们就返回什么
         */

        String driverClassName = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/mydb3";
        String mysqlUsername = "root";
        String mysqlPassword = "123456";

        Class.forName(driverClassName);
        Connection con = DriverManager.getConnection(url, mysqlUsername,
                mysqlPassword);
        Statement stmt = con.createStatement();
        // 目的是拼接成select * from t_user where username='zhangsan' and
        // password='123';这样一句话
        String sql = "select * from t_user where username='" + username
                + "'and password='" + password + "'";

        ResultSet rs = stmt.executeQuery(sql);//返回一条记录
        
        /*rs.last();
        System.out.println("记录数:"+rs.getRow());*/

        System.out.println(sql);
        return rs.next();
    }

    /*sql攻击*/
    @Test
    public void fun1() throws ClassNotFoundException, SQLException {

//        select * from t_user where username='a' or 'a'='a'and password='a' or 'a'='a'//sql语句,,废话  where条件为真
        String username="a' or 'a'='a";
        String password="a' or 'a'='a";
        boolean bl= login(username, password);
//        System.out.println(username+password);
        System.out.println(bl);
    }    

 防SQL注入:

 使用PreparedStatement

1.给出sql模板:所有的参数使用?来代替

2.调用Connection方法,得到PreparedStatement。

给模板中的?赋值pstmt.setString(int num,String "xx");

 1 ----boolean login2(String username,String password)方法
 2 String sql="select * from t_user where username=? and password=?";
 3         PreparedStatement pstmt=con.prepareStatement(sql);
 4         /*
 5          * 二、为参数赋值
 6          * 
 7          * */
 8         pstmt.setString(1, username);//给第一个问号赋值,值为username
 9         pstmt.setString(2, password);//给第二个问号赋值,值为password
10         
11         ResultSet rs= pstmt.executeQuery();
12         
13         return rs.next();
14 ============================
15 @Test
16     public void fun2() throws ClassNotFoundException, SQLException {
17 
18 //        select * from t_user where username='a' or 'a'='a'and password='a' or 'a'='a'//sql语句,,废话  where条件为真
19         String username="lisi";
20         String password="456";
21         boolean bl= login2(username, password);
22 //        System.out.println(username+password);
23         System.out.println(bl);
24     }
原文地址:https://www.cnblogs.com/xjs1874704478/p/10713024.html