我收到以下错误
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]))
请注意,您已重复参数一两次,如果异常来自数据库,那么这很可能是原因。
更多
IndexOutOfBoundsException在Java中是一个运行时异常。如文档中所述
Thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range. Applications can subclass this class to indicate similar exceptions.
很明显,您在没有先检查的情况下访问了数组的索引。总是一件危险的事情。
我也同意,您的 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]));
}
}
关于java - 使用java将csv文件导入oracle数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30023659/