I have a code which reads data from a file and inserts it into database.
this code writes the data into a file.
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) {
}
}
this code writes the data from the a file and inserts it into 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]+"')");
}
}
But it throws Exception
java.lang.ArrayIndexOutOfBoundsException
What is wrong?
arrayhas only one element",". It should have two or more to be able to usearray[1]andarray[2].