使用 opencsv 时出现 ArrayIndexOutOfBoundsException 错误

ArrayIndexOutOfBoundsException error when using opencsv

我希望有人能告诉我为什么会收到错误消息:"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1"

我正在使用 opencsv 从 csv 中插入数据,代码确实有效,因为数据已按预期插入到 table 中。但是我得到了错误。

下面是我的代码:

    PreparedStatement sql_statement = null;         
    String jdbc_insert_sql = "INSERT INTO wifi_users(email, first_name, last_name, gender, birthday, opted_in) VALUES (?, ?, ?, ?, ?, ?)";
    sql_statement = conn.prepareStatement(jdbc_insert_sql);

    /* Read CSV file in OpenCSV */
    String inputCSVFile = "/Users/Gerry/Documents/workspace/sql_out_connection/users.csv";
    CSVReader reader = new CSVReader(new FileReader(inputCSVFile));

    /* Variables to loop through the CSV File */
    String [] nextLine; /* for every line in the file */ 
    int lnNum = 0; /* line number */
    while ((nextLine = reader.readNext()) != null) {
            lnNum++;                    
            sql_statement.setString(1,(nextLine[0]));
            sql_statement.setString(2,(nextLine[1]));
            sql_statement.setString(3,(nextLine[2]));
            sql_statement.setString(4,(nextLine[3]));
            sql_statement.setString(5,(nextLine[4]));
            sql_statement.setDouble(6,Double.parseDouble(nextLine[5]));
            /* execute the insert statement */
            sql_statement.executeUpdate();
    }   

有人知道为什么我会收到此错误吗?

您的 CSV 文件中有一行少于预期的最小值 6 (0-5),因此出现 ArrayIndexOutOfBoundsException。

在继续更新数据库之前,您可能应该验证是否需要 6 个值。

顺便说一下,您不需要在值周围添加括号。最好这样...

sql_statement.setString(1, nextLine[0]);