我在学期开始之前练习Java,并且我尝试创建将在指定的CSV文件中读取的代码,并使用它创建数据库。但我收到的错误是
"线程中的异常" main" java.lang.ArrayIndexOutOfBoundsException:3
在LoadData.main(LoadKids.java:52)"
我的代码如下所示。
错误在这一行"评级=字段[3] .trim();"
import java.io.File;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class LoadData {
public static void main(String[] args) {
Connection c = null;
Statement s = null;
Scanner fromFile = null;
String sql1 = null, sql2 = null;
String line = null, ID = null, Console = null, Title = null, Rating = null, Multiplayer = null;
String[ ] fields;
try {
// Define Connection and Statement objects.
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:games.db");
s = c.createStatement();
// Instantiate scanner to read from file.
fromFile = new Scanner(new File ("FileName.csv"));
// Create the table.
sql1 = "create table if not exists " +
"games(gameid integer, " +
"ID varchar(2), " +
"Console varchar(15), " +
"Title varchar(20), " +
"Rating varchar(2), " +
"Multiplayer varchar(3));";
System.out.println("sql1: " + sql1);
s.executeUpdate(sql1);
// Read and throw away header line.
fromFile.nextLine( );
// Populate the table.
for (int id = 1001; fromFile.hasNextLine( ); id++) {
line = fromFile.nextLine( );
fields = line.split(" ");
ID = fields[0].trim();
Console = fields[1].trim();
Title = fields[2].trim();
Rating = fields[3].trim();
Multiplayer = fields[4].trim();
sql2 = String.format(
"insert into games (gameid, ID, Console, Title, Rating, Multiplayer) " +
"values (%d, '%s', '%s', '%s', '%s', '%s');",
id, ID, Console, Title, Rating, Multiplayer);
System.out.println(sql2);
s.executeUpdate(sql2);
}
c.close( );
}
catch (FileNotFoundException e) {
System.out.println("File queries.sql not found.");
System.err.println( e.getClass().getName() +
": " + e.getMessage() );
}
catch(SQLException e) {
System.out.println("SQLException.");
System.err.println( e.getClass().getName() +
": " + e.getMessage() );
}
catch (ClassNotFoundException e ) {
System.err.println( e.getClass().getName() +
": " + e.getMessage() );
}
finally {
fromFile.close( );
}
}
}
答案 0 :(得分:0)
请将数据发布到csv文件中。 通常,CSV文件以逗号分隔,因此名称以逗号分隔值。但是,您的代码使用空格来分隔值。
fields = line.split(" ");
如果您的CSV数据实际上以逗号分隔,请将该行更改为
fields = line.split(",");
如果您的CSV数据以空格分隔,请确认文件中每行至少有5个以空格分隔的项目。