如何在不必输入双引号的情况下制作搜索栏?

how to make search bar without having to type double quotation?

大家好,我正在尝试在 java 中创建此搜索栏,但是当我在不输入双引号的情况下进行搜索时,出现此错误

search error image

但是当我用双引号输入数字或单词时它工作得很好

searching with double quotation image

这是我的代码

Code image


private void jButton_Show1ActionPerformed(java.awt.event.ActionEvent evt) {                                              
      try{
          String Accounts_Choose_Value = jTextField1.getText();
          // Accounts_Choose_Value = (String) Accounts_jComboBox_Choose_Value.getSelectedItem();
                  
          if(Accounts_Choose_Value.equals(Accounts_Choose_Value)){
              String sql = "SELECT * FROM accounts WHERE URL="+Accounts_Choose_Value;
        con= DriverManager.getConnection("jdbc:mysql://localhost/accountmanagerdb","root","");
              Statement s = con.prepareStatement(sql);
              ResultSet rs =s.executeQuery(sql);
              if(rs.next()){
                  String Account_User_Name =rs.getString(2);
                  String Account_Email =rs.getString(3);
                  String Account_Password =rs.getString(4);
                  String Account_Backup_Codes =rs.getString(5);
                  
                  jLabel_Account_User_Name.setText(Account_User_Name);
                  jLabel_Account_Email.setText(Account_Email);
                  jLabel_Account_Password.setText(Account_Password);
                  jLabel_Account_Backup_Codes.setText(Account_Backup_Codes);
              }
          }
      } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(null, ex,
                            "Database",JOptionPane.ERROR_MESSAGE);        
      
      }
      
    }

我没有在文本字段中写任何东西

private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
    } 

改变这一行但是要注意SQL injection

String sql = "SELECT * FROM accounts WHERE URL=\""+Accounts_Choose_Value+"\"";

基本上,您需要将第一个查询生成的 where 子句条目用双引号引起来

SELECT * FROM accounts WHERE URL=google

这意味着您要给我所有列值 URL 等于列值 google

的行

正确的查询是

SELECT * FROM accounts WHERE URL="google"

现在你要求给我所有 URL 等于 "google" string

的行

在第一种情况下,您的代码失败说我找不到名为 google

的列

编辑

基本上你不应该直接对你的变量进行字符串插值,这会导致安全问题

你可以在这里参考如何做预处理语句

Java - escape string to prevent SQL injection