The resultset problem for retrieving databases in Java

Source: Internet
Author: User
During this time, I made a Java project and made an error while operating the database. Please refer to the following Program

... // Omitted in connection to the database
Resultset result = statement.exe cutequery (strsql );

// Start reading data and write it to the list
If (result. Next ()){
// Data available
Result. First ();

While (result. Next ()){
Lstdata. Add (result. getstring ("columname "));
}
}

As a result, the database is missing a piece of data. What is the problem?

A look at the help, it turned out to be the next problem, in the first execution result. before next (), the result does not point to the first row of data. After execution, it points to the first row of data. If the first row of data is 0, the result is executed for the first time. before next (), we can understand that the index pointed to by result is-1 (personal opinion), and the first () method also points the result to the first row of data, therefore, when the while loop is executed later, the data is retrieved from the second row. So the above program can be changed

If (result. Next ()){
// Data available
Result. First ();
Lstdata. Add (result. getstring ("columname "));

While (result. Next ()){
Lstdata. Add (result. getstring ("columname "));
}
}

In this way, there will be no errors, but the writing will always feel a little cumbersome, so I will change it to the following situation:

While (result. Next ()){
Lstdata. Add (result. getstring ("columname "));
}
// Check whether the data exists here
If (lstdata. Size ()> 0 ){
// Data available
} Else {
// No data
}

In combination with the above two methods, each method has its own applicable scenarios. If you just judge whether the data is directly used
If (result. Next ()){
// Data available
}
If the program needs to retrieve and process the data, the last method should be better.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.