0

I am hoping someone can enlighten me as to why I receiving the error: "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1"

I am using opencsv to insert data from a csv and the code does work, as in the data is inserted into the table as expected. However I get the error.

Below is my code:

    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();
    }   

Anyone have any idea why I get this error?

user1523236
  • 1,403
  • 3
  • 20
  • 43

1 Answers1

2

One of the lines in your CSV file has less than the expected minimum of 6 values (0-5), hence an ArrayIndexOutOfBoundsException.

You should probably validate that you require 6 values before proceeding with the database update.

You don't need the added parentheses around your values BTW. Better like this...

sql_statement.setString(1, nextLine[0]);
ManoDestra
  • 6,325
  • 6
  • 26
  • 50
  • Thanks Mano. You were correct, there was 1 line that was missing a comma between 2 values, thus been interpreted as 5 rather than 6. – user1523236 Mar 21 '16 at 21:24
  • Awesome. Glad that fixed it for you. Would you be happy to mark this as your answer then? :) – ManoDestra Mar 21 '16 at 21:25