【问题标题】:PreparedStatement continues to insert if Error如果出现错误,PreparedStatement 继续插入
【发布时间】:2018-05-07 13:32:07
【问题描述】:

我有点担心用 java 中的 Objet PreparedStatement 插入 Oracle 数据库。

感染我在 PreparedStatement 中准备好我的 INSERT 查询模型我为我要插入的每条记录添加了所有参数以及 addBatch()

例如,我添加了几个批次来插入 500 条记录。

在那之前它们都运行良好,我可以插入我想要的东西

另一方面,如果我的 PreparedStatement 在我要插入的 500 行上生成 BatchUpdateException 错误(例如违反约束),它不会向我插入任何内容完全没有。

我想限制删除引起关注的记录(带有违规约束)并至少插入可以的 499 行

我该怎么做?如果她能给我一首曲目,我将不胜感激。

仅供参考我想从500行中插入几行笔画,因此逐行插入的解决方案不适合我太多的性能水平。

真诚的

【问题讨论】:

  • doc。特别是:...JDBC 驱动程序可能会或可能不会继续处理剩余的命令...。如果您的驱动程序不提供支持,那么一种方法可能是捕获异常,然后逐行尝试该批次以隔离有问题的行。
  • 我试试这个,我遇到了同样的问题

标签: java oracle insert


【解决方案1】:

也许这不是你想要的,但 oracle 有一些内置的错误逻辑

你必须创建一个错误表 例如如果表被称为 emp,运行这个

exec dbms_errlog.create_error_log(dml_table_name=>'emp');

这将创建一个捕获错误的表 err$_emp

那么你可以在下面做这样的事情(注意日志错误进入子句)

批处理将成功,您必须在运行后检查错误表是否有错误

import java.sql.*;


public class Class1 {

    public static void main(String[] args) throws SQLException {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  

        PreparedStatement preparedStatement;
        int records = 20;

        try {
            Connection connection = DriverManager.getConnection(  
                    "jdbc:oracle:thin:@//host/db","scott","tiger");

            String compiledQuery = "INSERT INTO EMP(EMPNO)" +
                    " VALUES" + "(?) LOG ERRORS INTO ERR$_EMP REJECT LIMIT UNLIMITED";
            preparedStatement = connection.prepareStatement(compiledQuery);

            for(int index = 1; index <= records; index++) {
                preparedStatement.setInt(1, index);
                preparedStatement.addBatch();
            }

            long start = System.currentTimeMillis();

            int[] inserted;

            try {
                inserted = preparedStatement.executeBatch();
            }
            catch (SQLException e)
            {
                System.out.println("sql error");
            }
            long end = System.currentTimeMillis();

            System.out.println("total time taken to insert the batch = " + (end - start) + " ms");
            System.out.println("total time taken = " + (end - start)/records + " s");

            preparedStatement.close();
            connection.commit();
            connection.close();



        } catch (SQLException ex) {
            System.err.println("SQLException information");
            while (ex != null) {
                System.err.println("Error msg: " + ex.getMessage());
                ex = ex.getNextException();
            }
            throw new RuntimeException("Error");
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 2013-07-29
    • 1970-01-01
    相关资源
    最近更新 更多