PreparedStatement類對SQL注入問題的解決

1.Satement對象每執行一條SQL語句都會先將這條SQL語句發送給數據庫編譯,數據庫再執行。
  如果有1萬條類似的SQL語句,數據庫需要編譯1萬次,執行1萬次,顯然效率就低了。
  並且statement執行的是靜態的sql語句
2.prepareStatement()會先將SQL語句發送給數據庫預編譯。PreparedStatement會引用着預編譯後的結果。可以多次傳入不同的參數給PreparedStatement對象並執行。
  相當於調用方法多次傳入不同的參數
 
3.PreparedSatement的好處
prepareStatement()會先將SQL語句發送給數據庫預編譯。
PreparedStatement會引用着預編譯後的結果。
可以多次傳入不同的參數給PreparedStatement對象並執行。
減少SQL編譯次數,提高效率。
 
安全性更高,沒有SQL注入的隱患。
 
提高了程序的可讀性
 
PreparedSatement使用步驟? 1.獲取連接 2.先寫SQL語句帶?的 3.獲取PreparedStatement,預編譯 4.設置參數 5.執行SQL 6.關閉資源
PreparedSatement實現增刪查改使用哪個方法? executeUpdate(); 執行增刪改 exexuteQuery(); 執行查詢
/*
*
* sql注入:數據庫對用戶傳入的參數進行了編輯,改變了原本的sql的結構
*       預編譯:在用戶傳入參數之前先進行編譯,確定sql的結構,在傳入用戶的參數執行
*       1.select count(*) from user where username = ? and password = ?;
*       對於參數部分使用佔位符?
*       2.編譯完畢之後,確定了結構才傳入參數
*       3.對於用戶傳入的特殊字符參數,使用轉義,變成沒有實際意義的字符
* 
* 預編譯操作對象的獲取api:
*       PreparedStatement prepareStatement(String sql) 創建一個 PreparedStatement對象,用於將參數化的SQL語句發送到數據庫。
* */

1.executeQuery()方法,主要用DQL語句
public class LoginDemo {
    public static void main(String[] args) throws SQLException {
       

        Connection connection = JdbcUtil.getConnection();

        String sql = "SELECT count(*) FROM USER WHERE username = ? AND password = ? ;";
       
        //1.在用戶傳入參數之前先進行編譯,確定sql的結構
        PreparedStatement statement = connection.prepareStatement(sql);

        //2.預編譯完畢之後,再傳入用戶的參數
        statement.setString(1,username);
        statement.setString(2,password);

        //3.執行sql即可
        ResultSet resultSet = statement.executeQuery(); //注意:預編譯時,sql不用再傳,之前已經傳遞過了

        int count = 0;
        while (resultSet.next()) {
            count = resultSet.getInt("count(*)");
        }
        System.out.println(count >0 ? "登錄成功" :" 登錄失敗");

        JdbcUtil.release(resultSet,statement,connection);
    }
}


2.executeUpdate()方法,主要用於DML語句(update,delete,insert)
public class CRUDDemo {
    @Test
    public void insertTest() throws SQLException {

        Connection connection = JdbcUtil.getConnection();
        //使用預編譯進行數據的插入
        String sql = "INSERT  into USER  VALUES (?,?,?)";

        PreparedStatement statement = connection.prepareStatement(sql);

        statement.setInt(1,6);
        statement.setString(2,"liubei");
        statement.setString(3,"123456");

        int executeUpdate = statement.executeUpdate();
        System.out.println(executeUpdate);

        JdbcUtil.release(null,statement,connection);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章