Reputation: 11
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
Upvotes: 1
Views: 4604
Reputation: 20110
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).
Upvotes: 0
Reputation: 25873
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".
Upvotes: 0
Reputation: 347214
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);
}
Upvotes: 0
Reputation: 40318
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
Upvotes: 2