資料庫操作為什麼選PreparedStatement而不是Statement?
一、提高代碼可讀性,和可維護性
為什麼?直接上代碼statement.executeQuery("select id,name,age,sex from user where id>"+"id"+and name
like %"+subname+"%and sex="+sex+");
上面是使用statement對象的代碼
pstatement=connection.preparedStatement("select id,name,sex from user where id>?and
name like ? and sex=?");
pstatement.setString(1,id);
pstatement.setString(2,name);
pstatement.setString(3,sex);
pstatement.executeQuery();
上面是使用PreparedStatementd對象的代碼
雖然使用PreparedStatementd對象的代碼多了幾行,但是顯得更為簡潔。調理更為清晰,便於修改。
二、有助於提高性能
PreparedStatementd對象在創建時就指定了動態的SQL,因此這些SQL被編譯之後緩存起來了。等下一次再執行相同的預編譯語言時,就無需再對其進行編譯,只要將參數傳入就可以執行。動態SQL使用了「?」作為佔位符,因此預編譯語句的匹配率要比Statement對象使用的SQL語句大得多。
三、提高復用性
因為可以在佔位符處,每次通過傳入不同的參數對一個PreparedStatementd對象進行調用。
如果是使用statement對象,那麼每次要執行不同條件的SQL語句時,需要重新創建statement對象。
四、提高安全性
如果使用Statement對象,就很容易收到SQL注入攻擊。
如
String name="劉耀";
String sql="select * from user where name="+name+"";
statement.executeQuery(sql);
假設我將
String name=";drop table user;";
那麼實際上
執行的sql語句成了:select * from user where name=;dorp table user;
資料庫中user表就會被刪除。但是使用PreparedStatement對象就不會有這樣的危險。
推薦閱讀: