[英]How to compare user input with my database in java
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.如果在您的数据库中找不到name.getText()
的值,则rs.next()
将永远不会返回 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.由于您已将if
块包含在 while 循环中,因此如果在您的数据库中找不到匹配项,它将永远不会执行。 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.在此代码中,如果对rs.next()
的第一次调用返回false
,则我们不知道从数据库返回的任何内容。 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.在这种情况下,我将循环改为后检查do...while
循环,因为我们现在想在循环结束时检查rs.next()
。
Note: This answer demonstrates another way of checking whether the result set contains rows.注意:此答案演示了另一种检查结果集是否包含行的方法。
You should close the while() loop before the if/else.您应该在 if/else 之前关闭 while() 循环。
It is not the prettiest of code though.虽然它不是最漂亮的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.