天天看点

JDK6笔记(5)----JDBC4(4)

版权声明:本文为博主chszs的原创文章,未经博主允许不得转载。 https://blog.csdn.net/chszs/article/details/1556449

JDK6笔记(5)----JDBC4(4)

1、利用批处理更新

要提高性能,JDBC API提供了一个批处理更新方式,它允许你一次进行多种更新。

Statement、PreparedStatement、CallableStatement都支持批处理更新方式。

2、在Statement对象中使用批处理更新

Statement对象可以用单个的执行语句对DBMS进行一系列的更新。

Statement对象在初始化时,仅进行空批处理list的初始化;因此你必须调用Statement.addBatch方法来增加SQL命令到Statement对象。SQL命令必须返回一个update count,而不是别的任何类型。

要更好地处理批处理命令,你应该总是设置auto-commit(自动提交)为false,因此DBMS驱动只会在你告诉它需要做时它才进行提交。

这就给了一个清除批处理命令的chance,你可以使用Statement.clearBatch()方法来做,它将把Statement对象的所有批处理命令list。

如果批处理命令成功执行了,它将自动清除list。

当Statement.executeBatch()成功执行后,将返回一个update count的队列。它包含下面的东东:

1)为0或更大的值,它意味着命令得到了成功的处理。如果值大于0,它表示命令在执行后,受到影响的行数。

2)一个Statement.SUCCESS_NO_INFO,意味着特别的命令得到了成功处理。但是,它不包含任何信息,如受影响的行数等。

如果批处理命令执行失败,将抛出BatchUpdateException错误。某些数据库驱动可以继续进行下面的命令,但很多则是停止执行。

不是所有的JDBC驱动器都支持批处理更新。故在使用时你要注意看你的driver是否支持batch update。

如果你不清楚,用DatabaseMetaData.supportsBatchUpdates()方法来查看。

见下面一个例子:

try{

 //Make sure that autocommit is off

 cConn.setAutoCommit(false);

 //Retrieve metadata info about the data source

 DatabaseMetaData dbmData=cConn.getMetaData();

 //Make sure our driver supports batch updates

 if(dbmData.supportsBatchUpdates()){

  Statement sStatement=cConn.createStatement();

  //Add batch commands

  sStatement.addBatch("INSERT INTO TEAMS VALUES ('Tom')");

  sStatement.addBatch("INSERT INTO TEAMS VALUES ('Roger')");

  sStatement.addBatch("INSERT INTO TEAMS VALUES ('Jon')");

  sStatement.addBatch("INSERT INTO TEAMS VALUES ('Julia')");

  sStatement.addBatch("INSERT INTO TEAMS VALUES ('George')");

  int[] uCounts=sStatement.executeBatch();

  //Commit the changes

  cConn.commit();

 }else{

  System.err.print("Your driver does not support batch updates!")

  }

 }catch(BatchUpdateException batchEx){

  int[] uCounts=batchEx.getUpdateCounts();

  for(int i=0;i<uCounts.length;i++)

   System.err.print("Count #"+i+"="+uCounts[i]+"/n");

 }

3、在PreparedStatement对象中使用Batch Update

基本上与Statement中的方法相同,见下面的例子:

 //Make suer our driver supports batch updates

  PrparedStatement psStatement=cConn.prepareStatement("INSERT INTO TEAMS VALUES(?)");

  //Set the IN parameter

  psStatement.setString(1l"Jennie Vitale");

  //Add batch command

  psStatement.addBatch();

  //Set the IN parameter for the next command

  psStatement.setString(1,"Andrew Vitale");

  int[] uCounts=psStatement.executeBatch();

  System.err.print("Your driver does not support batch updates!");

}catch(BatchUpdateException batchEx){

}