java - 忽略异常,继续插入其余数据

标签 java mysql exception

我有以下代码片段。我删除了更多细节。我有一个包含所有数据的 for 循环。我运行 for 循环 for (int i = 0; i < list.getLength(); i++)。会发生什么情况是,当任何一个数据导致 sql 出错时说数据有斜杠等,然后它会导致异常并且 for 循环的其余部分无法继续。我怎样才能跳过异常并继续休息?

这是代码。

    Connection dbconn = null;
    Statement stmt1 = null;
    Statement stmt2 = null;
    try
    {
        dbconn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test1", "tes1", "te15");
        stmt1 = dbconn.createStatement();
        stmt2 = dbconn.createStatement();
        DateFormat outDf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = Calendar.getInstance().getTime();

        String value = null;
        for (int i = 0; i < list.getLength(); i++)
        {

            String insertCommand = "INSERT INTO command SET .........";
            System.out.println("\n SET INSERT :" + insertCommand);
            int count = stmt1.executeUpdate(insertCommand);
        }

    }
    catch (SQLException ex)
    {
        System.out.println("MyError Error SQL Exception : " + ex.toString());
    }
    catch (Exception rollback)
    {
        System.out.println("\nRollback :");
        rollback.printStackTrace(System.out);
    }
    catch (Exception e)
    {
        System.out.println("\n Error here :");
        e.printStackTrace(System.out);

    }
    finally
    {
        try
        {
            if (stmt1 != null)
            {
                stmt1.close();
            }

        }
        catch (SQLException ex)
        {
            System.out.println("MyError: SQLException has been caught for stmt1 close");
            ex.printStackTrace(System.out);
        }
        try
        {
            if (stmt2 != null)
            {
                stmt2.close();
            }

        }
        catch (SQLException ex)
        {
            System.out.println("MyError: SQLException has been caught for stmt2 close");
            ex.printStackTrace(System.out);
        }
        try
        {
            if (dbconn != null)
            {
                dbconn.close();
            }
            else
            {
                System.out.println("MyError: dbConn is null in finally close");
            }
        }
        catch (SQLException ex)
        {
            System.out.println("MyError: SQLException has been caught for dbConn close");
            ex.printStackTrace();
        }
    }

最佳答案

您需要将 try/catch block 放在 for 中,围绕 executeUpdate(insertCommand);

关于java - 忽略异常,继续插入其余数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38979889/

相关文章:

java - 组合 Java 性能

c# - 创建视频语音聊天应用程序的技巧

mysql - 使用 select、group by 和 count 时如何获得非空结果集?

mysql - mysqld 上的平均负载为 65,CPU 为 100%

php - 回复 : MySQL server not returning correct output

c++ - 为什么我不能在 Exception 类中有 auto_ptr

c++ - 如何在mingw中启用异常处理

java - 自动设置内容

java - 使用 Jackson 将转义的 json 解析为 JsonNode

java - 如何确定java中的数据库约束冲突?