Java, looping through result set

前端 未结 3 1280
滥情空心
滥情空心 2020-11-28 11:33

In Java, I have a query like this:

String querystring1= \"SELECT rlink_id, COUNT(*)\"
                   + \"FROM dbo.Locate  \"
                   + \"GROUP         


        
相关标签:
3条回答
  • 2020-11-28 12:12

    The problem with your code is :

         String  show[]= {rs4.getString(1)};
         String actuate[]={rs4.getString(2)};
    

    This will create a new array every time your loop (an not append as you might be assuming) and hence in the end you will have only one element per array.

    Here is one more way to solve this :

        StringBuilder sids = new StringBuilder ();
        StringBuilder lids = new StringBuilder ();
    
        while (rs4.next()) {
            sids.append(rs4.getString(1)).append(" ");
            lids.append(rs4.getString(2)).append(" ");
        }
    
        String show[] = sids.toString().split(" "); 
        String actuate[] = lids.toString().split(" ");
    

    These arrays will have all the required element.

    0 讨论(0)
  • 2020-11-28 12:18

    Result Set are actually contains multiple rows of data, and use a cursor to point out current position. So in your case, rs4.getString(1) only get you the data in first column of first row. In order to change to next row, you need to call next()

    a quick example

    while (rs.next()) {
        String sid = rs.getString(1);
        String lid = rs.getString(2);
        // Do whatever you want to do with these 2 values
    }
    

    there are many useful method in ResultSet, you should take a look :)

    0 讨论(0)
  • 2020-11-28 12:22
    List<String> sids = new ArrayList<String>();
    List<String> lids = new ArrayList<String>();
    
    String query = "SELECT rlink_id, COUNT(*)"
                 + "FROM dbo.Locate  "
                 + "GROUP BY rlink_id ";
    
    Statement stmt = yourconnection.createStatement();
    try {
        ResultSet rs4 = stmt.executeQuery(query);
    
        while (rs4.next()) {
            sids.add(rs4.getString(1));
            lids.add(rs4.getString(2));
        }
    } finally {
        stmt.close();
    }
    
    String show[] = sids.toArray(sids.size());
    String actuate[] = lids.toArray(lids.size());
    
    0 讨论(0)
提交回复
热议问题