As shown on the title, I have tried so hard to compare the user input with my database and it works with a true input. However, when the input is not exist on my database I don't know what is wrong in my below code, please help.
private class da implements ActionListener{
public void actionPerformed(ActionEvent e){
Connection con = null;
String url = "jdbc:mysql://localhost:3306/المكتبة";
String unicode = "?useUnicode=yes&characterEncoding=UTF-8";
try{
con = DriverManager.getConnection(url+unicode,"root","");
PreparedStatement upd = con.prepareStatement("SELECT * FROM library WHERE author =?'");
upd.setString(1,name.getText());
ResultSet rs = upd.executeQuery();
while(rs.next()){
String authorname = rs.getString("author");
String bookname = rs.getString("bookname");
String categort = rs.getString("category");
int isbn = Integer.parseInt(rs.getString("ISBN"));
String data = "اسم المؤلف: "+authorname+"\n"+"اسم الكتاب: "+bookname+"\n"+"التصنيف: "+categort+"\n"+"ISBN: "+isbn;
if(name.getText().equals(authorname))
txt.setText(data);
else
txt.setText("no matches");
The problem is related to this section:
while(rs.next()){
// ... other code
if(name.getText().equals(authorname))
txt.setText(data);
else
txt.setText("no matches");
If the value of name.getText()
is not found in your database, rs.next()
will never return true. Since you've enclosed your if
block inside of the while loop , it will never be executed if no match is found in your database. You could solve it a number of ways, one way is to do something like this instead:
boolean has_results = rs.next();
if(has_results){
do {
// ... your loop code
}while(rs.next());
}else {
text.setText("No Matches");
}
In this code, if the first call to rs.next()
returns false
, we know nothing we returned from the database. Otherwise, loop as normal. In this instance, I changed the loop to a post-checking do...while
loop instead, since we want to check rs.next()
at the end of the loop now.
Note: This answer demonstrates another way of checking whether the result set contains rows.
You should close the while() loop before the if/else.
It is not the prettiest of code though.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.