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

问题描述

大家好,我正在尝试在 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”字符串的所有行

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

编辑

基本上你不应该直接字符串插入你会导致安全问题的变量

你可以在这里参考如何做准备好的语句

Java - escape string to prevent SQL injection