因此,我一直试图创建一个String[][],使用JDBC从数据库中提取其项目,但是却无法将结果输入到String[][]中,我在做什么错了,我得到了这个错误:

java.lang.ArrayIndexOutOfBoundsException: 4
    at modelo.ConectorBaseDatos.getRows_From_DB(ConectorBaseDatos.java:194)
    at modelo.ConectorBaseDatos.main(ConectorBaseDatos.java:237)


194行是:

rows_list[rows][cols] = result.getString(2);


这是代码:

public String[][] getRows_From_DB(String tableName, String db, String querY){

            try{

                    int columnCount = this.getTableInfo(tableName, db, true, false) - 1;
                    int rowCount =  this.getTableInfo(tableName, db, false, true) - 1;

                rows_list = new String[rowCount][columnCount];

                Connection con = getConnect_to_DB("fifa");

                PreparedStatement statement  = con.prepareStatement(querY);

                ResultSet result = statement.executeQuery();

                while(result.next()){

                         for(int rows = 1; rows <= rowCount; rows++){

                                for(int cols = 1; cols <= columnCount; cols ++){

                                        rows_list[rows][cols] = result.getString(2);
                                        rows_list[rows][cols] = result.getString(3);
                                        rows_list[rows][cols] = result.getString(4);
                                        rows_list[rows][cols] = result.getString(5);
                                }
                         }
                }




            }catch(Exception e){
                e.printStackTrace();
                JOptionPane.showMessageDialog(null, "Error en getRows_From_DB()" + e, "ERROR!", JOptionPane.ERROR_MESSAGE, null);
            }

    return rows_list;
}

最佳答案

这里有几个问题:


您从1而不是0开始索引(如Kon所提到的)
您将给定的rows_list [rows] [cols]设置为4次(其中3次将替换实例)
您对行进行两次迭代(在结果集中返回一个,在使用行计数时第二次返回)。


请参阅以下解决这些问题的解决方案:

  ...
  ResultSet result = statement.executeQuery();

  int rowNumber = 0
  while(result.next()){
     //Alternatively iterate here in another loop through all columns.
     rows_list[rowNumber][0] = result.getString(2);
     rows_list[rowNumber][1] = result.getString(3);
     rows_list[rowNumber][2] = result.getString(4);
     rows_list[rowNumber][3] = result.getString(5);
  }
}catch(Exception e){
  ...

关于java - 数组超出范围..从mysql表创建多维数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23176527/

10-09 16:00
查看更多