伙计们,我正在努力为我正在开发的数据库创建搜索查询,但用户选择太多了!我不知道如何过滤掉它们!我是否必须为用户检查的每一个选择创建不同的查询?如果他只想搜索姓名,那就是另一个查询。姓名和姓氏是另一个。年龄和国家是另一回事!如果不编写数百行代码,我不知道该怎么做!我已经尝试过这个例子,但它只有在用户填写每个文本字段时才有效。
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);
}