0

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?

iminiki
  • 2,549
  • 12
  • 35
  • 45
  • 1
    Perhaps if you use `println` instead of `print`, you'll see 2 values printed, instead of a single value of twice the length. --- If you believe there is 1 record with status = 0, and nothing is printed, then check your assumptions, which includes making sure that any changes to the table have been committed. – Andreas Sep 26 '20 at 06:59
  • you should use re.hasNext() in the while cycle, get a value in the while as such String value = re.getString("uid") – Alexander Makarov Sep 26 '20 at 07:07
  • @AlexanderMakarov A result set has no `hasNext()` method. The use of `next()` as shown is the right usage. – Mark Rotteveel Sep 26 '20 at 08:27
  • code not run into {} of while loop, i don't know why? – Homerux Sep 26 '20 at 13:40
  • Edited the question in order to make it more sense. – iminiki Sep 28 '20 at 09:19

2 Answers2

0

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).

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
0

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.

osnineto
  • 11
  • 2