忽略异常并继续插入其余数据

时间:2016-08-16 16:21:10

标签: java mysql exception-handling

我有以下代码段。我删除了更多细节。我有一个包含所有数据的for循环。我为(int i = 0; i< list.getLength(); i ++)运行for循环。发生的事情是,当任何一个数据导致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();
        }
    }

2 个答案:

答案 0 :(得分:2)

您需要将try / catch块放在for executeUpdate(insertCommand);

周围

答案 1 :(得分:1)

您还需要在循环中捕获错误

....
for (int i = 0; i < list.getLength(); i++) {
    try {
        String insertCommand = "INSERT INTO command SET .........";
        System.out.println("\n SET INSERT :" + insertCommand);
        int count = stmt1.executeUpdate(insertCommand);
        } catch (Exception e) {
            // Better catch the real exception
            // Handle the exception 
        }
}
....