单击按钮后,表格中将显示表格中的所有记录。我在我的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){
}
}
答案 0 :(得分:0)
我认为"第一次"和#34;第二次"在原始问题中实际上代表" jTextField1值定义"和" jTextField2值已定义"。
生成的带有空jTextField2(名称)的SQL查询字符串将导致:
firstname LIKE '%'
OR
将匹配firstname不为NULL的所有记录,并且由于条件由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));
条件的影响非常小。
实际上"当存在时使用过滤器"如果相应的字段为空,我们需要排除条件:
import os, sys
os.system("make foo -f {}".format(" ".join(sys.argv[1:])))
我必须在此注意,整个内容仅用于教育目的,上述代码均不得用于制作。