1

How can I get all data in Mysql DB with JAVA

I Have this code but he get only first row

if (connection != null) {
System.out.println("You made it, take control your database now!");
        Statement st = connection.createStatement();
        String sql = ("SELECT * FROM nc;");
        ResultSet rs = st.executeQuery(sql);

        if(rs.next()) {
        int id = rs.getInt("id");
        String str1 = rs.getString("Name");
        String str2 = rs.getString("City");
System.out.format("%s, %s, %s\n", id, str1, str2);                 

and i get in the screen : id 0 , Name Nizar, City Casablanca

so how ican get all rows in my database and thank you

1
  • 3
    use while(rs.next()) Commented Jun 5, 2013 at 8:16

4 Answers 4

2

If you use if the block will execute only once.If you use while the block will execute until the condition false

use while instead of if

while(rs.next()) {
        int id = rs.getInt("id");
        String str1 = rs.getString("Name");
        String str2 = rs.getString("City");
System.out.format("%s, %s, %s\n", id, str1, str2);  
}


rs.next()  

will return false when all the records are completed

Sign up to request clarification or add additional context in comments.

1 Comment

We don't know it. The main mistake from the OP is he didn't ilterate through the resultset.
0

Change your if to a while...

while(rs.next()) {
    int id = rs.getInt("id");
    String str1 = rs.getString("Name");
    String str2 = rs.getString("City");
    System.out.format("%s, %s, %s\n", id, str1, str2);      
}

Comments

0

Replace if(rs.next()) by while(rs.next()).

if(rs.next()) means "if we have one result, move to it and do the following"

while(rs.next()) means "while we still have results, move to the next one and do the following".

Comments

0

You want to change your if (rs.next()) { To be a while(rs.next()) {

You're only iterating through one row as it is, that will iterate through all of them.

As a best practice, don't make the contents of the while(...) loop too fancy. You want to minimize the per-row processing while iterating, so the connection doesn't stay open too long. Many people just read rows into a List, or print them out (like you're doing).

Comments

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.