I want to get data from user and compare it with my database in java
as shown in the title, i tried so hard to compare user input to my database, it works with true input, but when input doesn't exist in my database, i dont know what is wrong in my below code, please help
private class da implements ActionListener{
public void actionPerformed(ActionEvent e){
Connection con = null;
Statement state = null;
Statement state2 = null;
ResultSet rs = null;
ResultSet rs2 = null;
String url = "jdbc:mysql://localhost:3306/المكتبة";
String unicode = "?useUnicode=yes&characterEncoding=UTF-8";
try{
con = DriverManager.getConnection(url+unicode,"root","");
state = con.createStatement();
state2 = con.createStatement();
rs = state.executeQuery("SELECT * FROM library WHERE author ='"+name.getText()+"'")
;
rs2=state2.executeQuery("SELECT * FROM library WHERE bookname ='"+title.getText()+"'");
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().trim().equals(authorname))
txt.setText(data);
else
txt.setText("dosen't exist");
}
while(rs2.next()){
String authorname = rs.getString("author");
String bookname = rs.getString("bookname");
String categort = rs.getString("category");
int isbn = Integer.parseInt(rs2.getString("ISBN"));
String data2 = "اسم المؤلف: "+authorname+"\n"+"اسم الكتاب: "+bookname+"\n"+"التصنيف: "+categort+"\n"+"ISBN: "+isbn;
txt.setText(data2);
}
}
catch(Exception t){
}
}}
}
+3
source to share
1 answer
First of all, don't use combining strings in sql queries, use PreparedStatement.
and try like this:
PreparedStatement upd = connect.prepareStatement("select * from library where author=?");
upd.setString(1,VariableToholdAuthor);
ResultSet rs = upd.executeQuery();
while(rs.next())
{
CompareVariable = rs.getString("name");
}
This will help you.
+1
source to share