java执行批更新

Statement, PreparedStatement CallableStatement 都有addBatch()方法用来把sql加入待处理的队列中。

executeBatch() 用来执行批处理,它返回一个数组,反映了每次更新的数据情况,由下面三个值:

  • EXECUTE_FAILED:抛出了一场,批处理过程出错.
  • SUCCESS_NO_INFO:语句没有返回相关被更新的数据数目.
  • 0 或者 更多:更新的数目.

看下面例子,如果批处理过程出错则会回滚所有:

Listing 7-11: Performing Batch Updates

// batch updates

例子:
import java.sql.*;

import java.io.*;

class SimpleExample

{

static DataInputStream stdin = new DataInputStream(System.in);



public static void main(String args[])

{

String url = "jdbc:odbc:mysource";

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection myConnection =

DriverManager.getConnection(url, "javauser", "hotjava");

myConnection.setAutoCommit(false);



Statement stmt = myConnection.createStatement();



String record = null;

try {

while ((record = stdin.readLine()) != null) {

String currency = record.substring(0,

record.indexOf(","));

String rate =

record.substring(record.indexOf(",") + 1);



String sql = "UPDATE currencies SET

rate = " +

rate + " WHERE currency = ‘" +

currency + "‘";

stmt.addBatch(sql);

}

stmt.executeBatch();

myConnection.commit();

} catch (BatchUpdateException e) {

System.out.println("An exception occurred after

" + e.getUpdateCounts() + " updates.");

myConnection.rollback();

}

myConnection.close();

}

catch(java.lang.Exception ex)

{

ex.printStackTrace();

}

}

}


 

 

 

你可能感兴趣的:(java,sql,jdbc,sun)