Statement對象是用來執行SQL語句的
PreparedStatement:預編譯的Statement對象,是Statement的子接口。
一.性能和代碼編寫的簡潔程度方面
它允許數據庫預編譯SQL語句(這些SQL語句通常有帶有參數),以后每次只需改變SQL命令的參數,避免數據庫每次都需要編譯SQL語句,提高了性能。 e.g. 連接數據庫部分
//已定義好driver、url、user、passwd等//加載驅動Class.forName(driver);//獲得連接Connection conn = DriverManager.getConnection(url, user, passwd);
Statement:
//用Connection創建一個StatementStatement stmt = conn.createStatement() { //100條SQL語句來插入100條記錄 for(int i = 0;i < 100;i++) { stmt.executeUpdate("insert into student values(" + "null, 'aaa" + i + "',90)"); }}
PreparedStatement:
//用Connection創建一個PreparedStatementPreparedStatement pstmt = conn,getPreparedStatement("insert into student_table values(null, ?, 90)") { //設置參數,100次傳入參數而不是100次傳入SQL語句 for(int i = 0;i < 100;i++) { pstmt.setString(1, "姓名" + i); //執行 pstmt.executeUpdate(); }}
通過運行以上的代碼可以發現,PreparedStatement插入100條記錄所用的時間比Statement插入100條記錄所花費時間少。而且可以在代碼中可以看出,帶有參數的SQL語句,創建Statement對象需要對參數進行拼接,但是PreparedStatement會簡潔很多。
完整代碼移步GitHub:Statement&PrepareStatement
運行結果:
二.安全方面
又因為PreparedStatement不需要拼接,還可以防止SQL注入從而提高安全性
注:SQL注入是一種Cracker入侵方式,從SQL語句的漏洞入侵
比如一個登錄頁面,我們在獲取表單傳來的參數,將其與數據庫中的數據進行比對,比對有該賬號密碼時則登錄成功:
Statement:
//傳入參數username和passwd是提交的信息String sql = "select * from users " + "where username = ' " + username + " ' and password= ' " + passwd + " ';rs = stmt.executeQuery(sql);
如果在username框中輸入了:'or true or',那么,拼接后的SQL語句就變成了:
select * from users where username = ' ' or true or ' ' and desc = ' ';
結果為true被SQL當成直接量那么直接會登錄成功
PreparedStatement:
//傳入參數username和passwd是提交的信息PreparedStatement pstmt = conn.getPreparedStatement("select * from users where username = ? and password= ?");pstmt.setString(1, username);pstmt.setString(2, passwd);
從上述可以看出PreparedStatement相較于Statement有三個好處:
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對VeVb武林網的支持。
新聞熱點
疑難解答
圖片精選