Printing a result set doesn't show all rows

914 Views Asked by At

I have some codes line as

Class.forName("com.mysql.cj.jdbc.Driver");
            connect = DriverManager
                    .getConnection("jdbc:mysql://localhost/"+Contant.DB_NAME+"?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&"
                            + "user="+Contant.MYSQL_USER+"&password="+Contant.MYSQL_PASS);  
            statement = connect.createStatement();
          preparedStatement = connect.prepareStatement("select * from history where status = 0");
           re = preparedStatement.executeQuery();
          while (re.next()) {
                System.out.print("uid__"+re.getString("uid"));
            }

In my database, I have 2 rows that meet the condition status = 0.

When executing System.out.print("uid__"+re.getString("uid")); it only shows one row. What am I doing wrong?

2

There are 2 best solutions below

2
On

By default the PrintWriter assigned to System.out is buffered, which means it will collect characters and flush them if its buffer is full, or if content with a new-line character was added.

As you use System.out.print, there is no new-line character. To get your prints to show, you need to print more so the buffer is full, or you need to use System.out.println("uid__"+re.getString("uid")); (so each uid is on its own line, and flushed automatically), or - after the loop - add a System.out.println(); (which will flush automatically) or System.out.flush() (an explicit flush).

0
On

I think you may be jumping the first line of the result of your query, try to set your cursor before the result begins by using re.beforeFirst().

When you go to your while condition by calling re.next(), you are moving your cursor to the next line of the results, which means that if you are in the first line of your result set, it will go to second line when it goes inside the while loop. You can also try to use do {} while () instead of while.