I am trying to use variable in select query with like clause but getting an error like invalid identifier. Here is my method...
private void searchBooks(){
try{
String SEARCHFORTHIS=Find_Book_Field.getText();
pst=conn.prepareStatement("SELECT * FROM BOOK WHERE NAME LIKE '%'+ SEARCHFORTHIS +'%'");
rs=pst.executeQuery();
Show_All_Books.setModel(DbUtils.resultSetToTableModel(rs));
}catch(SQLException e){
e.printStackTrace();
JOptionPane.showMessageDialog(null,e);
}
}
NEVER use string concatenation to build a SQL statement with user-supplied text values.
Well, unless you really want your code to be susceptible to SQL Injection attacks, allowing a hacker to steal your data and delete your tables.
You're already using PreparedStatement
, so use it right.
You should also use try-with-resources for correct resource management.
private void searchBooks() {
String SEARCHFORTHIS = Find_Book_Field.getText();
String sql = "SELECT * FROM BOOK WHERE NAME LIKE ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, "%" + SEARCHFORTHIS + "%");
try (ResultSet rs = stmt.executeQuery()) {
Show_All_Books.setModel(DbUtils.resultSetToTableModel(rs));
}
} catch (SQLException e){
e.printStackTrace();
JOptionPane.showMessageDialog(null,e);
}
}
Try this
try{
String SEARCHFORTHIS=Find_Book_Field.getText();
pst=conn.prepareStatement("SELECT * FROM BOOK WHERE NAME LIKE '%"+ SEARCHFORTHIS +"%'");
rs=pst.executeQuery();
Show_All_Books.setModel(DbUtils.resultSetToTableModel(rs));
}catch(SQLException e){
e.printStackTrace();
JOptionPane.showMessageDialog(null,e);
}
}
Made changes in SELECT query only. you have not properly closed the double quote in it.
Note : completely agree with Andreas, we should use Preparedstatment, in this kind of scenarios, to prevent SQL Injection attacks.
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.