有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

mysql如何在java中创建包含多个可选where子句的搜索语句?

以下是一般搜索的代码:

     int row = jTable_accounts.getSelectedRow();
    String Table = (jTable_accounts.getModel().getValueAt(row, 0).toString());
      String sql ="select c.customer_id as 'Customer No.', customer_name as 'Name',a.account_id as 'Account No.',DIA,a.balance as 'Current Balance',a.outstanding_amt as'Outstanding Amt.' from customer c inner join customer_details cd on cd.customer_id=c.customer_id inner join account a on a.customer_id=c.customer_id where a.account_id= '"+Table+"' ";

所以结果将显示在一个jtable中,但是,我想添加4或5个文本框,它们应该根据客户名称过滤结果,未付金额等。这些文本框应为可选条目,如果用户未在任何文本框中输入任何值,应用程序应显示一般输出(上述代码)

我假设select语句中应该添加一些where子句,但我不确定它应该是可选的

以下是三个表格,以获取更多信息:

顾客:

     customer_id     DIA     customer_name             birth_date    
     --------------  ------  ------------------------  ------------- 
     1               32       Ahmad mohammad bin afif  (null)        
     2               10       mohammad ahmad bin afif   (null) 

客户信息:

     customer_id     phone_no1     phone_no2     address_line1     address_line2    
     --------------  ------------  ------------  ----------------  ---------------- 
     1               0111231415    019123443     bukit             (null)           
     2               01345532      (null)        kl                serdang  

账户:

    account_id     balance     outstanding_amt     customer_id    
    -------------  ----------  ------------------  -------------- 
    1              12530.23    1821.3              1              
    2              2040.13     125.3               1              
    3              213455      1234.3              2                            

共 (1) 个答案

  1. # 1 楼答案

    你应该检查文本框中的值是否为空,如果不是,你可以在查询中构建额外的过滤器

    例如

    if (textField1.getValue().trim().length > 0) {
      query += " and COLUMN1 = " + textField1.getValue().trim() + " ";
    }
    if (textField2.getValue().trim().length > 0) {
      query += " and COLUMN2 = " + textField2.getValue().trim() + " ";
    }
    

    。 .

    由于您有一个基本查询,其中声明了一个“where”语句,因此只需检查文本字段是否为空,即可添加“and”语句