我想在一个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)
我想知道是哪个 docName 导致了这个错误,但我不知道应该如何在 catch 中编写显示 docName 的消息。因为 docName 在 catch 正文中未定义。
我不是 Java 和 MySQL 方面的专家,所以我的代码可能基于错误的基础。请帮助我理解我的错误
最佳答案
这是基于我的 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();
}
或者,您可以在 for-each
循环的每次迭代开始时递增 i
,以避免在 catch 中减去:
for (String docName : docNames){
i++;
preparedStmt.setString(1,docName);
关于java - 在插入 MySQL 表期间为 try catch 编写特殊异常消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34051674/