JDBC 02: 登录校验
1. Version 1
容易引发sql注入的问题,造成非法访问
1 package com.Jasper2003.jdbc01; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import java.sql.Statement; 8 9 public class JDBCDemo01 { 10 public static void main(String[] args) { 11 System.out.println(selectByUsernamePassword("siki","123")); 12 } 13 14 public static boolean selectByUsernamePassword(String username,String password) { 15 Connection con = null; 16 Statement stmt = null; 17 ResultSet rs = null; 18 19 try { 20 Class.forName("com.mysql.jdbc.Driver"); 21 22 String url = "jdbc:mysql://localhost:3306/web01?useUnicode=true&CharacterEncoding=UTF8&useSSL=false"; 23 con = DriverManager.getConnection(url,"root","root"); 24 stmt = con.createStatement(); 25 26 String sql = "select * from user where username = '"+username+"' and password = '"+password+"'"; 27 rs = stmt.executeQuery(sql); 28 29 if(rs.next()) { 30 return true; 31 }else { 32 return false; 33 } 34 }catch (Exception e) { 35 e.printStackTrace(); 36 } finally { 37 38 try { 39 if(rs!=null) 40 rs.close(); 41 } catch (SQLException e) { 42 e.printStackTrace(); 43 } 44 45 try { 46 if(stmt!=null) 47 stmt.close(); 48 } catch (SQLException e) { 49 e.printStackTrace(); 50 } 51 52 try { 53 if(con!=null) 54 con.close(); 55 } catch (SQLException e) { 56 e.printStackTrace(); 57 } 58 } 59 return false; 60 } 61 }
引发sql注入问题后的sql语句和其结果:
2. Modified Version: Use prepared statement
1 public static boolean selectByUsernamePassword(String username,String password) { 2 Connection con = null; 3 Statement stmt = null; 4 ResultSet rs = null; 5 6 try { 7 Class.forName("com.mysql.jdbc.Driver"); 8 9 String url = "jdbc:mysql://localhost:3306/web01?useUnicode=true&CharacterEncoding=UTF8&useSSL=false"; 10 con = DriverManager.getConnection(url,"root","root"); 11 stmt = con.createStatement();
String sql = "select * from user where username = ? and password = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
rs = pstmt.executeQuery();
16 if(rs.next()) { 17 return true; 18 }else { 19 return false; 20 } 21 }catch{ 22 // Omitted 23 } finally{ 24 // Omitted 25 }
return false; 26 }