谁能告诉我这里做错了什么?我运行了大约100次,大约2-8次失败并出现错误:java.lang.ArrayIndexOutOfBoundsException: 10
public String[][] queryResult(String QUERY) throws SQLException{
Connection con = getPoolConnection();
Statement st2 = con.createStatement();
ResultSet rs = st2.executeQuery(QUERY);
System.out.println("Run query: "+QUERY);
// outPrint(logFile,"Run query: "+QUERY+"");
ResultSetMetaData metaData = rs.getMetaData();
int noOfColumns = metaData.getColumnCount();
//System.out.print(metaData.toString()+" : ");
this.columnName = new String[noOfColumns];
this.columnTypes = new String[noOfColumns];
for (int i = 1; i <= noOfColumns; i++) {
this.columnName[i-1] = metaData.getColumnLabel(i);
this.columnTypes[i-1] = metaData.getColumnTypeName(i);
System.out.print(this.columnName[i-1]+" - "+this.columnTypes[i-1]+" , ");
}
System.out.println(" - ");
rs.last();
int noOfRows = rs.getRow();
rs.beforeFirst();
String[][] result = new String[noOfRows][noOfColumns];
int loop = 0;
while(rs.next()) {
loop++;
for (int i = 1; i <= noOfColumns; i++) {
result[loop-1][i-1] = getResultSwitch(metaData.getColumnType(i), rs, i);
//System.out.println("result "+this.columnTypes[i-1]+" : "+result[loop-1][i-1]);
System.out.print(result[loop-1][i-1]+" , ");
}
System.out.println(" - ");
}
rs.close();
st2.close();
con.close();
//System.out.println("Closed connection.");
return result;
}
答案 0 :(得分:0)
我建议您不要使用rs.last()
和rs.getRow()
创建静态数组,而是建立结果行的ArrayList,并在完成后将其转换为数组。
System.out.println(" - ");
//rs.last();
//int noOfRows = rs.getRow();
//rs.beforeFirst();
//String[][] result = new String[noOfRows][noOfColumns];
List<String[]> tempResult = new ArrayList<String[]>();
//int loop = 0;
while(rs.next()) {
//loop++;
String[] row = new String[noOfColumns];
for (int i = 0; i < noOfColumns; i++) {
row[i] = getResultSwitch(metaData.getColumnType(i+i), rs, i);
//System.out.println("result "+this.columnTypes[i-1]+" : "+result[loop-1][i-1]);
//System.out.print(result[loop-1][i-1]+" , ");
tempResult.add(row);
}
System.out.println(" - ");
}
rs.close();
st2.close();
con.close();
//System.out.println("Closed connection.");
return tempResult.toArray(new String[0][noOfColumns]);
答案 1 :(得分:-3)
虽然我不知道哪行代码会引发此异常,但我发现代码中至少存在一个问题:
result[loop-1][i-1]
第一次迭代时,loop-1为-1,因为loop = 0