当AutoCommit设置为false时,为什么我没有收到BatchUpdateException?

时间:2015-06-26 13:01:13

标签: sql-server jdbc

在下面的代码中,当自动提交设置为true时,我得到BatchUpdateException,当设置为false时,我得到SQLServerException。为什么? (代码如下)。

自动提交时的堆栈跟踪:

java.sql.BatchUpdateException: Conversion failed when converting the nvarchar value 'hello' to data type int.
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeBatch(SQLServerPreparedStatement.java:1178)
    at dbconnect.main(dbconnect.java:48)

自动提交= false时的堆栈跟踪:

com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converting the nvarchar value 'hello' to data type int.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1515)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatementBatch(SQLServerPreparedStatement.java:1299)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtBatchExecCmd.doExecute(SQLServerPreparedStatement.java:1209)
    at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:180)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:155)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeBatch(SQLServerPreparedStatement.java:1173)
    at dbconnect.main(dbconnect.java:48)

那么在使用auto-commit = false时,如何检查批处理中的哪个语句导致批处理失败。

Microsoft SQL Server与名为bot的表一起使用,其中包含2个整数列。 在代码中,我手动批量生成一个语句。

  System.out.println("Connecting to database...");
  conn = DriverManager.getConnection(DB_URL,USER,PASS);

  stmt=conn.createStatement();
  conn.setAutoCommit(false);
  PreparedStatement ps = conn.prepareStatement("INSERT into bot VALUES (?,?)");

  long start,end;
  try
  {
      for(int i=0;i<100;i++)
      {
          if(i==50)
          {
              ps.setInt(1, i);
              //ps.setInt(2,i+1000);
              ps.setString(2,"hello");
              ps.addBatch();
              continue;
          }
          ps.setInt(1, i);
          ps.setInt(2,i+1000);
          ps.addBatch();
      }

      int [] result = ps.executeBatch();
      conn.commit();
  }
  catch(SQLException e)
  {
      System.out.println("Error       :");
      e.printStackTrace();

      //conn.rollback();
  }

0 个答案:

没有答案