在MySQL表格中插入期间为try catch编写特殊异常消息

时间:2015-12-02 19:48:16

标签: java mysql try-catch

我想根据以下代码在MySQL表中插入信息:

public void writeMapDocNameToDocId(File file, ArrayList<String> docNames) {
            PreparedStatement preparedStmt= null;
            try{
                conn.setAutoCommit(false);
                String query = " insert into DocumentNameId (docName)"
                        + " values (?)";
                preparedStmt = conn.prepareStatement(query);
                int i=0;


                for (String docName : docNames) 
                { 
                    preparedStmt.setString (1, docName);
                    preparedStmt.addBatch();
                    i++;
                    if (i % 1000 == 0 || i == docNames.size()) {
                        preparedStmt.executeBatch(); 
                    }
                }
                conn.commit();
                preparedStmt.close();
                conn.setAutoCommit(true);
            }
            catch(Exception e){
                e.printStackTrace();
            }

        }

我的某些DocName出现以下错误。

java.sql.BatchUpdateException: Data truncation: Data too long for column 'docName' at row 1
    at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1269)
    at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:955)
    at dataLayer.RepositorySQL.writeMapDocNameToDocId(RepositorySQL.java:508)

我想知道哪些docNames导致了这个错误,但是我不知道如何在catch中编写显示docName的消息。因为,docName在catch body中是未定义的。

我不是java和MySQL的专家,因此我的代码可能基于错误的基础。请帮我理解我的错误

1 个答案:

答案 0 :(得分:1)

以下是代码中的插图,基于我上面的comment

int i=0; //Declare i outside of your try-catch statement

try{
    ...
    for (String docName : docNames){ 
        preparedStmt.setString (1, docName);
        preparedStmt.addBatch();
        i++;
        if (i % 1000 == 0 || i == docNames.size()) {
            preparedStmt.executeBatch(); 
        }
    }
    ...
}
catch(Exception e){

    String docNameError = docNames.get(i - 1); 
    //subtract 1 from i, because i is only incremented after a successful add 
    //to your prepared statement.

    //use docNameError however you'd like to report the exception

    e.printStackTrace();
}

或者,您可以在i循环的每次迭代开始时递增for-each,以避免捕获中的减法:

for (String docName : docNames){
    i++;
    preparedStmt.setString(1,docName);