一、Statement(存在SQL注入问题)

  1. public static void main(String[] args) {
  2. // login("lili","123");
  3. login(" 'or' 1=1"," 'or' 1=1");
  4. }
  5. public static void login(String name,String pwd){
  6. Connection conn = null;
  7. Statement st = null;
  8. ResultSet rs = null;
  9. try{
  10. conn = jdbcUtils.getConnection(); // 获取数据库连接
  11. st = conn.createStatement(); // 获取SQL的执行对象
  12. String sql="SELECT * FROM userinfo WHERE username='"+name+"' AND password='"+pwd+"';";
  13. System.out.println(sql);
  14. rs = st.executeQuery(sql);
  15. while (rs.next()){
  16. System.out.println(rs.getString("username"));
  17. System.out.println(rs.getString("password"));
  18. System.out.println("======================");
  19. }
  20. } catch (SQLException throwables) {
  21. throwables.printStackTrace();
  22. }finally {
  23. jdbcUtils.release(conn,st,rs);
  24. }
  25. }

二、PreparedStatement(解决SQL注入问题)

  1. public static void main(String[] args) {
  2. // login("lili","123");
  3. login("'' or 1=1","'' or 1=1");
  4. }
  5. public static void login(String name,String pwd){
  6. Connection conn = null;
  7. PreparedStatement st = null;
  8. ResultSet rs = null;
  9. try{
  10. conn = jdbcUtils.getConnection(); // 获取数据库连接
  11. /*
  12. prepareStatement 防止注入的本质,把传递过来的参数当做字符
  13. 假设集中存放转义字符,比如说 ' 会被直接转义
  14. */
  15. String sql="SELECT * FROM userinfo WHERE username=? AND password=?";
  16. st = conn.prepareStatement(sql); // 获取SQL的执行对象
  17. st.setString(1,name);
  18. st.setString(2,pwd);
  19. rs = st.executeQuery(); // 查询完毕会返回一个结果集
  20. while (rs.next()){
  21. System.out.println(rs.getString("username"));
  22. System.out.println(rs.getString("password"));
  23. System.out.println("======================");
  24. }
  25. } catch (SQLException throwables) {
  26. throwables.printStackTrace();
  27. }finally {
  28. jdbcUtils.release(conn,st,rs);
  29. }
  30. }