我收到以下错误
Java.lang.ArrayIndexOutOfBoundsException: 0
at oracle.jdbc.driver.OracleSql.main(OracleSql.java:1614)
我正在使用eclipse indigo和oracle 10g。我该如何解决此问题。有人可以帮助我吗?
我想将一个csv文件加载到oracle数据库中。.我创建了一个名为zt的表,该表具有三列(id,s_date,data)。CSV数据包含以下内容:
a1,2015-04-15 17:40:20.0,18.5786
a2,2015-04-15 16:20:59.0,16.7868
a3,2015-03-15 16:20:59.0,16.51689
a4,2015-04-16 16:20:55.0,24.789028
a5,2015-02-15 17:55:59.0,28.784145
代码
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import au.com.bytecode.opencsv.CSVReader;
public class ImportTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
readCsv();
}
public static void readCsv() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn =DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521/xe","system","arry");
PreparedStatement pstmt =conn.prepareStatement("Insert into zt values(?,?,?)");
CSVReader reader = new CSVReader(new FileReader("D:\\zzzzzzzz.csv"), ',');
String[] nextLine;
int i = 0;
while((nextLine = reader.readNext()) != null) {
i++;
pstmt.setString(1,nextLine[0]);
pstmt.setString(2,nextLine[1]);
pstmt.setDouble(3,Double.parseDouble(nextLine[2]));
}
pstmt.close();
conn.commit();
conn.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
对于初学者来说
pstmt.setString(1,nextLine[0]);
pstmt.setString(1,nextLine[1]);
pstmt.setDouble(2,Double.parseDouble(nextLine[2]))
请注意,您重复了两次参数一,如果数据库发出异常,则很可能是原因。
而且
Java中的IndexOutOfBoundsException是运行时异常。如文档中所述
表示某种索引(例如,数组,字符串或向量)的索引超出范围。应用程序可以将该类作为子类来指示类似的异常。
显然,您无需先检查即可访问数组的索引。总是很危险的事情。
我也同意,您的CSV文件似乎不正确,但是您遇到的任何问题都不仅限于此,您应该对此加以防范。我添加了代码以显示基本的防护措施
只需在您的while循环中检查长度,如下所示
while((nextLine = reader.readNext()) != null){
i++;
// Remember length 3 = index 2
if (nextLine.length == 3){
pstmt.setString(1,nextLine[0]);
//I have changed it to 2 from 1
pstmt.setString(2,nextLine[1]);
pstmt.setDouble(2,Double.parseDouble(nextLine[2]));
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句