1. 程式人生 > 實用技巧 >解決SQL注入問題

解決SQL注入問題

PreparedStatement和Statement的區別:

/**
 * 1、對比一下Statement和PreparedStatement?
     * statement存在sq1注入問題,PreparedStatement解訣了sql注入問題。
     * Statement是編譯一次執行一 次。PreparedStatement是編譯一次, 可執行N次。                    
     * PreparedStatement會在編譯階段做型別的安全檢查。
 * 綜上所述: PreparedStatement使用較多。只有極少數的情況下需要使用Statement
 * 2、什麼情況下必須使用Statement呢?
     * 業務方面要求必須支援sQL注入的時候。
     * Statement支援sQL注入,凡是業務方面要求是需要進行sq1語句拼接的,必須使用Statement 
 
*/

程式碼:

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Test08_解決SQL注入問題 {
    public static void main(String[] args) {
        //初始化一個介面的方法
        Map<String,String> userLogin = chuShiHuaUi();
        //驗證使用者名稱和密碼
        Boolean dengLu = login(userLogin);
        
//最後輸出結果 System.out.println(dengLu ? "登入成功!" : "登入失敗!"); } private static Boolean login(Map<String, String> userLogin) { //打標記 Boolean b = false; Connection conn = null; //PreparedStatement 是Statement的一個介面 PreparedStatement ps = null; ResultSet rs
= null; try{ //1、註冊驅動 Class.forName("com.mysql.jdbc.Driver"); //2、獲取連線 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/donglijiedian","root","zhixi158"); //3、獲取 預編譯 的資料庫操作物件 // sQL語句的框子。其中一個?,表示一個佔位符,一個?將來接收一個“值”, 注意:佔位符不能使用單引號括起來。 String sql = "select * from t_user where userName = ? and userPwd = ?"; //程式執行到此處,會發送sq1語句框子給DBMS,然後DBMS進行sql語句的預先編譯。 ps = conn.prepareStatement(sql); //給佔位符?傳值(第1個問號下標是1,第2個問號下標是2,JDBC中 所有下標從1開始。) ps.setString(1,userLogin.get("userName")); ps.setString(2,userLogin.get("userPwd")); //4、執行SQL rs = ps.executeQuery(); //5、處理查詢結果集 //使用者名稱錯的情況下查不到記錄,使用者名稱正確情況下也最多查出一條記錄,所以用if就夠了 if(rs.next()){ return true;//如果存在這條記錄就返回 } }catch(Exception e){ e.printStackTrace(); }finally { //6、釋放資源,由內到外 try{ if(rs != null) rs.close(); }catch(Exception e){ e.printStackTrace(); } try{ if(ps != null) ps.close(); }catch(Exception e){ e.printStackTrace(); } try{ if(conn != null) conn.close(); }catch(Exception e){ e.printStackTrace(); } } return b; } private static Map<String, String> chuShiHuaUi() { Scanner s = new Scanner(System.in); //獲取使用者名稱 System.out.println("使用者名稱:"); String userName = s.nextLine();//nextLine返回一行資料 //獲取密碼 System.out.println("密碼:"); String userPwd = s.nextLine(); //組裝Map集合 Map<String,String> userLogin = new HashMap<>(); userLogin.put("userName",userName);//獲取使用者名稱 userLogin.put("userPwd",userPwd);//獲取密碼 return userLogin;//返回集合資料 } }