将MySQL表中的行存储到Java中的数组中

时间:2014-02-18 14:31:25

标签: java mysql arrays

我正在尝试将表中的行存储到数组中。我可以得到第一个结果并存储,但我似乎无法存储任何其他数据。

这是我写的代码

try 
    {
        test = "select * from Arsenal order by 'MatchNumber' ASC";                
        rs = st.executeQuery(test); 

        while (rs.next()) 
        {
            //This retrieves each row of Arsenal table and adds it to an array in the Team Results class.

            matchno = rs.getString("MatchNumber");                    
            hometeam = rs.getString("HomeTeam");                      
            awayteam = rs.getString("AwayTeam");                         
            homegoals = rs.getString("HomeGoals");                   
            awaygoals = rs.getString("AwayGoals");                   
            result = rs.getString("Result");                             


            teams = (matchno + "," + hometeam + "," + awayteam + "," + homegoals + "," + awaygoals + "," + result);     // Takes all the variables containging a single customers information and puts it into a string, seperated by commas.
            TeamResults.add(matchno,hometeam,awayteam,homegoals,awaygoals,result);
        }
    }

知道我哪里出错了?

3 个答案:

答案 0 :(得分:0)

while - 条件更改为hasNext()并使用循环内的next()向前移动数据库光标。

答案 1 :(得分:0)

尝试使用此方法:

 public void SelectData(String sqlcounter ,String sql){

        try {
         RsCounter=stmt.executeQuery(sqlcounter);
            System.out.println(sqlcounter);
            while(RsCounter.next()){

                countrow=RsCounter.getInt("COUNTR");
                System.out.println(countrow+"\n");
                             }
            System.out.println(sql);
         RsSelecting = stmt.executeQuery(sql);
         data=new String[countrow][RsSelecting.getMetaData().getColumnCount()];

         header= new String[RsSelecting.getMetaData().getColumnCount()];

     i=0;
     while(RsSelecting.next()){
      for(j=0;j<RsSelecting.getMetaData().getColumnCount();j++){

              data[i][j]=(RsSelecting.getString(j+1));
              header[j]=RsSelecting.getMetaData().getColumnName(j+1);
              System.out.print(data[i][j]+"\n");

     }    


      i++;

     }
      i=j=0;
        } catch (SQLException ex) {
                       ex.printStackTrace();

            Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
        }
   }

其中

sqlcounter ="select COUNT(*) as COUNTR from Arsenal order by 'MatchNumber' ASC";

sql ="select * from Arsenal order by 'MatchNumber' ASC";

答案 2 :(得分:0)

验证列名称一次。有时ALIAS无效,我不确定原因。

从结果集中获取元数据:

ResultSetMetaData metaData = resultSet.getMetaData();
int size = metaData.getColumnCount();

for (int i = 0; i < size; i ++)
    System.out.println(metaData.getColumnName(i);

同样仅针对性能,列出列名而不是*查询中使用SELECT。此外,您可以查看com.sun.rowset.CachedRowSetImpl.它的使用方式如下:

CachedRowSetImpl crs = new CachedRowSetImpl();
crs.populate(resultSet);

我认为它也实现了CachedRowSet,但我并不完全确定。