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