2016-03-21 55 views
0

我希望当有人可以告诉我,为什么我收到错误:“异常线程‘main’java.lang.ArrayIndexOutOfBoundsException:1”ArrayIndexOutOfBoundsException异常错误使用opencsv

我使用opencsv从插入数据一个csv和代码确实工作,因为数据按预期插入到表中。但是我得到的错误。

下面是我的代码:

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

任何人有任何想法,为什么我得到这个错误?

回答

2

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

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

您不需要围绕您的值添加括号顺便说一句。更好的是这样的...

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

感谢马诺。你是对的,有1行在2个值之间缺少一个逗号,因此被解释为5而不是6. – user1523236

+0

太棒了。很高兴为您解决它。你会很乐意把这个标记为你的答案吗? :) – ManoDestra

相关问题