[英]Java - Out of Bounds Exception Database
我在學期開始之前正在練習Java,並且嘗試創建將在指定的CSV文件中讀取的代碼,並使用它創建數據庫。 但是我得到一個錯誤,說
“線程“主”中的異常” java.lang.ArrayIndexOutOfBoundsException:3
在LoadData.main(LoadKids.java:52)“
我的代碼在下面列出。
該行的錯誤是“ Rating = fields [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( );
}
}
}
請將數據發布到您的csv文件中。 通常,CSV文件用逗號分隔,因此名稱用逗號分隔。 但是,您的代碼使用空格分隔值。
fields = line.split(" ");
如果您的CSV數據確實用逗號分隔,請將該行更改為
fields = line.split(",");
如果您的CSV數據用空格分隔,請確認文件中的每一行至少有5個項目用空格分隔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.