`
wjheye
  • 浏览: 82125 次
  • 性别: Icon_minigender_1
  • 来自: 河南
社区版块
存档分类
最新评论

深入 理解 Statement 和 PreparedStatement

阅读更多
一、使用Statement而不是PreparedStatement对象
JDBC驱动的最佳化是基于使用的是什么功能. 选择PreparedStatement还是Statement取决于你要怎么使用它们. 对于只执行一次的SQL语句选择Statement是最好的. 相反, 如果SQL语句被多次执行选用PreparedStatement是最好的.

PreparedStatement的第一次执行消耗是很高的. 它的性能体现在后面的重复执行. 例如, 假设我使用Employee ID, 使用prepared的方式来执行一个针对Employee表的查询. JDBC驱动会发送一个网络请求到数据解析和优化这个查询. 而执行时会产生另一个网络请求. 在JDBC驱动中,减少网络通讯是最终的目的. 如果我的程序在运行期间只需要一次请求, 那么就使用Statement. 对于Statement, 同一个查询只会产生一次网络到数据库的通讯.

对于使用PreparedStatement池的情况下, 本指导原则有点复杂. 当使用PreparedStatement池时, 如果一个查询很特殊, 并且不太会再次执行到, 那么可以使用Statement. 如果一个查询很少会被执行,但连接池中的Statement池可能被再次执行, 那么请使用PreparedStatement. 在不是Statement池的同样情况下, 请使用Statement.

二、使用PreparedStatement的Batch功能
Update大量的数据时, 先Prepare一个INSERT语句再多次的执行, 会导致很多次的网络连接. 要减少JDBC的调用次数改善性能, 你可以使用PreparedStatement的AddBatch()方法一次性发送多个查询给数据库. 例如, 让我们来比较一下下面的例子.


例 1: 多次执行Prepared Statement
PreparedStatement ps = conn.prepareStatement(   
   "INSERT into employees values (?, ?, ?)");   
   
for (n = 0; n < 100; n++) {   
   
  ps.setString(name[n]);   
  ps.setLong(id[n]);   
  ps.setInt(salary[n]);   
  ps.executeUpdate();   
}   


例 2: 使用Batch

PreparedStatement ps = conn.prepareStatement(   
   "INSERT into employees values (?, ?, ?)");   
   
for (n = 0; n < 100; n++) {   
   
  ps.setString(name[n]);   
  ps.setLong(id[n]);   
  ps.setInt(salary[n]);   
  ps.addBatch();   
}   
ps.executeBatch();   


在例 1中, PreparedStatement被用来多次执行INSERT语句. 在这里, 执行了100次INSERT操作, 共有101次网络往返. 其中,1次往返是预储statement, 另外100次往返执行每个迭代. 在例2中, 当在100次INSERT操作中使用addBatch()方法时, 只有两次网络往返. 1次往返是预储statement, 另一次是执行batch命令. 虽然Batch命令会用到更多的数据库的CPU周期, 但是通过减少网络往返,性能得到提高. 记住, JDBC的性能最大的增进是减少JDBC驱动与数据库之间的网络通讯.
  注:Oracel 10G的JDBC Driver限制最大Batch size是16383条,如果addBatch超过这个限制,那么executeBatch时就会出现“无效的批值”(Invalid Batch Value) 异常。因此在如果使用的是Oracle10G,在此bug减少前,Batch size需要控制在一定的限度。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics