单击按钮后,表格中将显示表格中的所有记录

问题描述 投票:-1回答:1

当我单击按钮时,表格中的所有记录都显示在表格中。我在我的sql查询中使用了like和equal运算符,它第一次在将所有数据检索到表时第二次工作吗?谁能告诉我代码中有什么问题?

 try{
            String url="jdbc:sqlserver://localhost:1433;databaseName=gym2 ";
                String username = "mali";
                String password = "12345";
                Connection con =DriverManager.getConnection(url,username,password);
                Statement st = con.createStatement ();
                ResultSet rs;
                String empid =jLabel3.getText()+jTextField1.getText();
                String name = jTextField2.getText();
               // String d =jComboBox1.getSelectedItem().toString();
       String sql = "SELECT emp_id,firstname,designation,full_address,gender,land,monthly_sal FROM employee_reg where (emp_id = '"+empid+"' or firstname LIKE '"+name+"%')";


        rs= st.executeQuery(sql);
       jTable1.setModel(DbUtils.resultSetToTableModel(rs));
            }
            catch(Exception e){

            } 
        }                 
java sql database sql-like
1个回答
0
投票

我认为原始问题中的“第一次”和“第二次”实际上代表“jTextField1值定义”和“jTextField2值定义”。

生成的带有空jTextField2(名称)的SQL查询字符串将导致:

SELECT emp_id,firstname,designation,full_address,gender,land,monthly_sal
FROM employee_reg where (emp_id = '...' or firstname LIKE '%');

firstname LIKE '%'将匹配firstname不为NULL的所有记录,并且因为条件由OR分隔,所以emp_id = '...'条件的影响非常小。

要实际“在使用时使用过滤器”场景,我们需要在相应字段为空时排除条件:

String     url       = "jdbc:sqlserver://localhost:1433;databaseName=gym2 ";
String     username  = "mali";
String     password  = "12345";
Connection con       = DriverManager.getConnection(url,username,password);
Statement  st        = con.createStatement ();
ResultSet  rs;

// Prepare the whole emp_id condition string
String     empidCond = " or emp_id = '" + jLabel3.getText()+jTextField1.getText() + "'";
// Clear it if jTextField1 is empty
if(jTextField1.getText().isEmpty()) {empidCond = "";}

// Prepare the whole firstname condition string
String     nameCond  = " or firstname LIKE '" + jTextField2.getText() + "%'";
// Clear it if jTextField2is empty
if(jTextField2.getText().isEmpty()) {nameCond = "";}
// String d          = jComboBox1.getSelectedItem().toString();

// Create SQL statement with one "stub" condition always false
// to "chain" the other conditions to
String sql = "SELECT emp_id,firstname,designation,full_address,gender,land,monthly_sal "+
             "FROM employee_reg "+
             "WHERE 1=2" + empidCond + nameCond;

rs = st.executeQuery(sql);
jTable1.setModel(DbUtils.resultSetToTableModel(rs));

我必须在此注意,整个内容仅用于教育目的,并且上述代码都不应用于生产。

© www.soinside.com 2019 - 2024. All rights reserved.