Statement和PrepareStatement区别

网上很多都说区别是PrepareStatement可以批处理。实际上二者都是可以进行批处理的。
区别在于:
1.PrepareStatement要求预编译的sql必须是格式固定,使用占位符获取参数。
   效率比较高,防sql注入,安全性较高。
2.Statement对sql格式并无要求,因此比较灵活。但是PrepareStatement效率更高。
 
什么叫做防sql注入?
密码输入1' or '1'='1
String sql = " select * from 用户表 where username='name' and pass='1' or '1'='1'";
我们会发现如何输入什么都是可以查询到信息,这样不安全。
但是PrepareStatement不会
String sql = " select * from 用户表 where username='name' and pass='1' or '1'='1''";
 
 
 
Connection conn = DBPool. getConnection();
conn.setAutoCommit( false );
sql = " update 客户渠道静态表 set col_1_1_4_48=?, col_1_1_4_47=?," +
      " col_1_1_4_49='"+User_Name+"',col_1_1_4_50=sysdate" +
      " where col_1_1_4_1=?";
PreparedStatement  ps = conn.prepareStatement(sql);
 for(int i = 1 ; i < sheet.getLastRowNum ()+1 ; i++ ){
     HSSFRow row = sheet.getRow(i);
     ps.setString(1, row.getCell(12).getStringCellValue());
     ps.setString(2, row.getCell(13).getStringCellValue());
     ps.setString(3, row.getCell(0).getStringCellValue());
     ps.addBatch();
}
ps.executeBatch();
conn.commit();
conn.close();
PreparedStatement

Connection conn = DBPool. getConnection();
conn.setAutoCommit( false );
Statement stamt = conn.createStatement();
for(int i = 1 ; i < sheet.getLastRowNum()+1 ; i++ ){
     HSSFRow row = sheet.getRow(i);
     sql = " update 客户渠道静态表 set col_1_1_4_48='"+row.getCell(12).getStringCellValue()+ "'," +
           " col_1_1_4_47='"+row.getCell(13).getStringCellValue()+ "'," +
           " col_1_1_4_49='"+User_Name+"',col_1_1_4_50=sysdate" +
           " where col_1_1_4_1='"+row.getCell(0).getStringCellValue()+ "'";
     stamt.addBatch( sql);
}
stamt.executeBatch();
conn.commit();
conn.close();
Statement

 

posted @ 2014-04-04 16:42  爱笑的狐狸  阅读(981)  评论(0编辑  收藏  举报