Convert Resultset to String array

前端 未结 5 922
死守一世寂寞
死守一世寂寞 2021-01-05 03:16

I need to Convert My result set to an array of Strings. I am reading Email addresses from the database and I need to be able to send them like:

message.addRe         


        
相关标签:
5条回答
  • 2021-01-05 03:43

    you do not need arr = em.split("\n"); since you are looping through each row (assuming that 1 row = 1 email address ) you just need this :

            ArrayList<String> arr = new ArrayList<String>();
            while (rs.next()) {
               arr.add(rs.getString("EM_ID"));
               System.out.println(arr.get(arr.size()-1));
            }
    
    0 讨论(0)
  • 2021-01-05 03:46
    import java.util.List;
    import java.util.ArrayList;
    
    List<String> listEmail = new ArrayList<String>();
    
    while (rs.next()) {
        listEmail.add(rs.getString("EM_ID"));
    }
    //listEmail,toString() will look like this: [abc@abc.com, abc@def.com]
    //So lets replace the brackets and remove the whitspaces
    //You can do this in less steps if you want:
    String result = listEmail.toString();
           result = result.replace("[", "\"");
           result = result.replace("]", "\"");
           result = result.replace(" ", "");
    
    //your result: "abc@abc.com,abc@def.com"
    //If the spaces are e problem just use the string function to remove them
    

    Btw you may should use BCC instead of CC in terms of privacy....

    Also you should never use SELECT * FROM foo; Better use SELECT EM_ID FROM foo; This gives you a significant Performance increase in a huge Table, since the ResultSet just consists of the information you really need and use...

    0 讨论(0)
  • 2021-01-05 03:57

    to get the desired output:

    replace these lines

    String[] arr = null;
    while (rs.next()) {
        String em = rs.getString("EM_ID");
        arr = em.split("\n");
        for (int i =0; i < arr.length; i++){
            System.out.println(arr[i]);
        }
    }
    

    by

    String arr = null;
    while (rs.next()) {
        String em = rs.getString("EM_ID");
        arr = em.replace("\n", ",");
        System.out.println(arr);
    }
    
    0 讨论(0)
  • 2021-01-05 03:59

    If i understand correctly You want to see the output in one line with comma as a separator. Then instead of

    System.out.println(arr[i]);
    

    Try

    System.out.print(arr[i]+",");
    

    and remove last comma somehow.

    0 讨论(0)
  • 2021-01-05 04:00
    System.out.println(arr[i]);
    

    Instead use:

    System.out.print(arr[i] + ",");
    
    0 讨论(0)
提交回复
热议问题