0

I have a database table with columns : name, residence, contact. and I want to retrieve only the values in the 'contact column' into an array. the following code is what I wrote:

List l = new ArrayList();
try {
    String sql = "select * from members";
    pst = conn.prepareStatement(sql);
    rs = pst.executeQuery();
    while (rs.next()) {
        String con = rs.getString("Contact");
        l.add(con);
        System.out.println(l);
    }
} catch (Exception e) {
    e.getMessage();
}

but this generates the following result:

[0547615632]
[0547615632, 0246687643]
[0547615632, 0246687643, 0558581764]

whilst I have only 3 records in the table and each having a contact value.
please how do I write the code so that I can get only a single array displaying the result like this:

[0547615632, 0246687643, 0558581764]

thank you very much.

3
  • change query to Select contact from members Commented Mar 19, 2018 at 12:35
  • I did that bro, but I still get the same 3 arrays. Commented Mar 19, 2018 at 12:38
  • 1
    because you print the array on every iteration. either print the array after the loop of only print the current element. shown in the answer below Commented Mar 19, 2018 at 12:39

1 Answer 1

2

You should move the print command out of the while loop:

List l = new ArrayList();
try {
    String sql = "select * from members";
    pst = conn.prepareStatement(sql);
    rs = pst.executeQuery();
    while (rs.next()) {
        String con = rs.getString("Contact");
        l.add(con);
    }
} catch (Exception e) {
    e.getMessage();
}
System.out.println(l);

OR only print the current element in each iteration;

List l = new ArrayList();
try {
    String sql = "select * from members";
    pst = conn.prepareStatement(sql);
    rs = pst.executeQuery();
    while (rs.next()) {
        String con = rs.getString("Contact");
        l.add(con);
        System.out.print(con + " ");
    }
} catch (Exception e) {
    e.getMessage();
}
Sign up to request clarification or add additional context in comments.

4 Comments

thank you very much @Emre Acer, it worked perfectly. thank you all
bro please guide me.. am quite new in stack over flow. please where do I go and what link do I have to click on to accept your answer @EmreAcer
I searched through it bro.. I don't think I have earned the privilege to accept an answer. cos I don't see any options available for me to do that. are u on facebook
@RodneyNart it doesn't require privilege but its ok my friend. Im happy that i solved your problem. Good luck !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.