来看一下代码,首先看statement的,当然现在已经几乎没人用了,首先这里使用拼接语句,直接将id带入查询而Statement每次执行sql语句都是进行编译导致的产生
//接受传参//接受传参String id=request.getParameter("id");//链接数据库Class.forName("com.mysql.jdbc.Driver");Connection conn=DriverManager.getConnection("jdbc:mysql://localhost/codeaudit","root","root");Statement statement=conn.createStatement();//执行SQL语句ResultSet rs=statement.executeQuery("select * from news where id="+id);//显示内容while(rs.next()){out.print("
"+"
");out.println("ID:"+rs.getString(1)+"
");out.println("标题:"+rs.getString(2)+"
");out.println("内容:"+rs.getString(3)+"
");out.print("
");}
实际结果如下图:
下面在说prepareStatement,因为prepareStatement是预编译的并且具有过滤sql注入的功能从而很安全,但是如果是拼接字符串还是会出问题
代码
//接受传参String id=request.getParameter("id");//链接数据库Class.forName("com.mysql.jdbc.Driver");Connection conn=DriverManager.getConnection("jdbc:mysql://localhost/codeaudit","root","root");//执行SQL语句PreparedStatement ps=conn.prepareStatement("select * from news where id=?"+id);ResultSet rs=ps.executeQuery();//显示内容while(rs.next()){out.print("
"+"
");out.println("ID:"+rs.getString(1)+"
");out.println("标题:"+rs.getString(2)+"
");out.println("内容:"+rs.getString(3)+"
");out.print("
");}
测试图:
其实PreparedStatement有提供给我们一个(1,999)的方法给我们
//执行SQL语句PreparedStatement ps=conn.prepareStatement("select * from news where id=?");ps.setString(1, id);ResultSet rs=ps.executeQuery();
从而避免了sql注入的产生
好在介绍一种在登录出如果使用了拼接字符串的问题
Login.html
账号:
密码:
sql_injection.jsp
String id=request.getParameter("id");String pw=request.getParameter("pw");Class.forName("com.mysql.jdbc.Driver");Connection conn=DriverManager.getConnection("jdbc:mysql://localhost/codeaudit","root","root");PreparedStatement ps=conn.prepareStatement("select * from admin where username='"+id+"' && password='"+pw+"'");ResultSet rs=ps.executeQuery();if(rs.next()){out.println("登陆成功");}else{out.println("账号或密码错误");}
测试如图:
上面的代码因为拼接的问题导致了万能密码的出现,所以在实际开发中我们一定要避免拼接字符串的代码
应该使用prepareStatement提供的(1,999)
PreparedStatement ps=conn.prepareStatement("select * from admin where username=? && password=?");ps.setString(1, id);ps.setString(2, pw);ResultSet rs=ps.executeQuery();