我有一个代码从文件中读取数据并将其插入数据库。
此代码将数据写入文件。
public void save(Collection<Book> b) {
try (PrintWriter print = new PrintWriter(this.file);) {
for (Book book : b) {
String str = book.getName() + "," + book.getAuthor() + ","
+ book.getDate() + "\n";
print.println(str);
}
} catch (Exception e) {
}
}
此代码从a文件写入数据并将其插入db。
try(Reader reader = new FileReader(this.file);
BufferedReader br = new BufferedReader(reader)) {
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/myBook", this.userName,
this.pass);
Statement statement = connection.createStatement();
String str;
while((str = br.readLine()) != null){
String[] array = str.split(",");
statement.executeUpdate("Insert Into myBook.book (name,author,pubDate) values('"+array[0]+"', '"+ array[1]+"', '"+array[2]+"')");
}
}
但它会抛出异常
java.lang.ArrayIndexOutOfBoundsException
有什么问题?
答案 0 :(得分:1)
执行以下操作:
array[2]
似乎某个行或迭代的数组没有3个项目,可能是一个或两个。
示例:
line 1: aaa,bbb,ccc //2 ',' => array={"aaa","bbb","ccc"} this is fine
line 2: ddd,eee //1 ',' => array={"ddd","eee"} this causes the
// exception since array[2] does not exist NULL
line 3: empty //0 ',' => array={} this causes the exception
如果您不确定发生了什么,请运行以下代码:
try(Reader reader = new FileReader(this.file);
BufferedReader br = new BufferedReader(reader)) {
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/myBook", this.userName,
this.pass);
Statement statement = connection.createStatement();
String str;
while((str = br.readLine()) != null&&str.split(",").length>=3){
String[] array = str.split(",");
statement.executeUpdate("Insert Into myBook.book
(name,author,pubDate) values('"+array[0]+"', '"+ array[1]+"', '"+array[2]+"')");
}
}
如果上面的代码运行没有错误,那么至少有一行没有2','chars 如果应用程序仍然触发相同的错误,那么它将是其他内容。