伙计我正在努力为我正在开发的数据库创建搜索查询,但用户选择太多了!我不知道如何过滤掉它们!我是否必须为用户检查的每个单一选项创建不同的查询?如果他只想搜索名称,那就是另一个查询。姓名是另一个。年龄和国家是另一个!如果不写几百行代码,我不知道怎么做!我尝试了这个例子,但只有当用户填写每个文本字段时它才有效。
private void searchB_actionPerformed(ActionEvent e) {
query = "SELECT agent_id, name, surname, clearance, user_id, alias, missions, age, country, current_mission FROM agents WHERE " ;
if (!agentidTF.getText().isEmpty()) {
query = query + "agent_id = '" + agentidTF.getText() + "' ";
//System.out.println(query);
if (!nameTF.getText().isEmpty()) {
query = query + " AND name = '" + nameTF.getText().toUpperCase() + "' ";
//System.out.println(query);
if (!surnameTF.getText().isEmpty()) {
query = query + " AND surname = '" + surnameTF.getText().toUpperCase() + "' ";
//System.out.println(query);
if (clearancebox.getSelectedItem() != "SELECT CLEARANCE") {
query =
query + " AND clearance = '" + clearancebox.getSelectedItem().toString().toUpperCase() +
"' ";
//System.out.println(query);
if (!useridTF.getText().isEmpty()) {
query = query + " AND user_id = '" + useridTF.getText() + "' ";
//System.out.println(query);
if (!ageTF.getText().isEmpty()) {
query = query + " AND age = '" + ageTF.getText() + "' ";
//System.out.println(query);
if (!aliasTF.getText().isEmpty()) {
query = query + " AND alias = '" + aliasTF.getText().toUpperCase() + "' ";
//System.out.println(query);
if (!currmissTF.getText().isEmpty()) {
query =
query + " AND current_mission = '" + currmissTF.getText().toUpperCase() +
"' ";
//System.out.println(query);
if (countrybox.getSelectedItem() != "SELECT COUNTRY") {
query =
query + " AND country = '" + countrybox.getSelectedItem().toString().toUpperCase() +
"' ";
//System.out.println(query);
} //end of countrybox
} //end of currmissTF
} //end of aliasTF
} //end of ageTF
} //end of useridTF
} //end of clearancebox
} //end of surnameTF
} //end of nameTF
} //end of agentidTF
query = query + " ORDER BY agent_id";
System.out.println("ACTUALL QUERY IS: " + query);
}