您的位置:首页 > 数据库

JDBC的SQL注入漏洞分析和解决

baixueniang 2019-10-22 11:46 751 查看

1.1.1 SQL注入漏洞分析


1.1.2 SQL注入漏洞解决

需要采用PreparedStatement对象解决SQL注入漏洞。这个对象将SQL预先进行编译,使用?作为占位符。?所代表内容是SQL所固定。再次传入变量(包含SQL的关键字)。这个时候也不会识别这些关键字。

public class UserDao {

         

        public boolean login(String username,String password){

                Connection conn = null;

                PreparedStatement pstmt = null;

                ResultSet rs = null;

                // 定义一个变量:

                boolean flag = false;

                try{

                        // 获得连接:

                        conn = JDBCUtils.getConnection();

                        // 编写SQL语句:

                        String sql = "select * from user where username = ? and password = ?";

                        // 预编译SQL

                        pstmt = conn.prepareStatement(sql);

                        // 设置参数:

                        pstmt.setString(1, username);

                        pstmt.setString(2, password);

                        // 执行SQL语句:

                        rs = pstmt.executeQuery();

                        if(rs.next()){

                                // 说明根据用户名和密码可以查询到这条记录

                                flag = true;

                        }

                }catch(Exception e){

                        e.printStackTrace();

                }finally{

                        JDBCUtils.release(rs, pstmt, conn);

                }

                return flag;

        }
标签: