PreparedStatement和Statement比较
生活随笔
收集整理的這篇文章主要介紹了
PreparedStatement和Statement比较
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在選擇使用Statement時,會產生SQL注入:
@Testpublic?void?testSave(){String?name?=?"a'?or?1=1?or?1='";String?password?="123";Connection?conn?=?null;Statement?st?=?null;ResultSet?rs?=?null;conn?=?DBUtil.getCon();//String?sql?=?"select?*?from?s_user?where?id=100";try?{st?=?conn.createStatement();String?sql?=?"select?*?from?users?where?username='"+name+"'and?password='"+password+"'";System.out.println(sql);rs?=?st.executeQuery(sql);while(rs.next()){System.out.println(rs.getString(1));}}?catch?(SQLException?e)?{//?TODO?Auto-generated?catch?blocke.printStackTrace();}}這回顯示登錄成功。
但是如果使用PreparedStatement:
@Testpublic?void?testSave(){String?name?=?"a'?or?1=1?or?1='";String?password?="123";Connection?conn?=?null;PreparedStatement?pstmt?=?null;ResultSet?rs?=?null;conn?=?DBUtil.getCon();String?sql?=?"select?*?from?users?where?username=???and?password=?";try?{pstmt?=?conn.prepareStatement(sql);pstmt.setString(1,?name);pstmt.setString(2,?password);rs?=?pstmt.executeQuery();if(rs.next()){System.out.println(rs.getInt(1));}else{System.out.println("fuck");}}?catch?(SQLException?e)?{//?TODO?Auto-generated?catch?blocke.printStackTrace();}}效率方面:
使用Statement:
@Testpublic?void?testEff(){Connection?conn?=null;Statement?stmt?=?null;conn?=?DBUtil.getCon();long?time?=?System.currentTimeMillis();try{stmt?=?conn.createStatement();for(int?i=0;i<5000;i++){String?sql?=?"insert?into?users?(username,password)?values?('1','123')";stmt.executeUpdate(sql);}??????????System.out.println(System.currentTimeMillis()-time);}catch(Exception?e){}}輸出為:122482 使用PreparedStatement: @Testpublic?void?testEff()?{Connection?conn?=?null;PreparedStatement?pstmt?=?null;long?time?=?System.currentTimeMillis();conn?=?DBUtil.getCon();conn?=?DBUtil.getCon();String?sql?=?"insert?into?users?(username,password)?values?(?,?)";try?{pstmt?=?conn.prepareStatement(sql);for?(int?i?=?0;?i?<?5000;?i++)?{pstmt.setString(1,?"t");pstmt.setString(2,?"1233");pstmt.executeUpdate();}System.out.println(System.currentTimeMillis()-time);}?catch?(Exception?e)?{}} 輸出為:135199 效率來說,PreparedStatement和Statement在mysql里,PreparedStatement不比Statement好。總結
以上是生活随笔為你收集整理的PreparedStatement和Statement比较的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: struts2模型驱动和令牌拦截器
- 下一篇: struts2文件上传(2)