MySQL——sql注入理解

简单理解sql注入是什么意思:“即将sql中的关键字当做参数注入到sql中,改变其原有sql的语义。”

展开举例:

在我们常见的登录业务中,我们最简单的做法就是拿用户输入的用户名和密码去数据库中进行匹配,如下:

state.executeQuery("select * from user where username ='" + username + "'and password ='" + password + "')");

 当我们正常输入用户名和密码时:

例如:
张三    123

拼接后sql语句为:
select * from user where username='张三' and password='123';

找到则结果集的next()会返回true,没找到则会返回false;

但是我们通过sql注入的方式,把1' or '1'='1 作为密码进行输入,如下:

例如:
张三   1' or '1'='1

拼接后sql语句为:
select * from user where username='张三' and password='1' or '1'='1';

 我们会发现:sql语句注入了or条件,使其原有的查询条件作废了,因为1=1恒成立,不管前面是什么条件。

到这应该已经理解博文的第一句话:将sql中的关键字当做参数注入到sql中,改变其原有sql的语义

 代码扩展:

public boolean login(String username, String password) {
        Connection conn = null;
        Statement state = null;
        ResultSet rs = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8", "root", "123");
            state = conn.createStatement();
            rs = state.executeQuery("select * from user where username ='" + username + "'and password ='" + password + "')");
            return rs.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                state.close();
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }
public boolean login(String username, String password) {
        Connection conn = null;
        PreparedStatement pstate = null;
        ResultSet rs = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8", "root", "123");
            //参数: 预编译的SQL语句, 参数部分使用?替代.
            pstate = conn.prepareStatement("select * from user where username=? and password=?");
            //向预编译的执行环境中, 加入参数的内容
            pstate.setString(1,username);
            pstate.setString(2,password);
            //执行
            rs = pstate.executeQuery();
            return rs.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                rs.close();
                pstate.close();
                conn.close();
            } catch (Exception throwables) {
                throwables.printStackTrace();
            }
        }
        return false;
    }

 

你可能感兴趣的:(MySQL,mysql,java)