JAVA设置根据“ComboBox”的值设置字符串



我试图通过使用基于用户选择的ComboBox的字符串的列名来搜索数据库,我分配一个基于用户选择的字符串,当我在SQL语句中输入字符串为NULL时。请帮忙,谢谢!下面是我的代码:

String[] searchOptions={"ID","First Name","Middle Name","Last Name","Gender","Date of Birth","Nationality","Contact number"};
JComboBox comboBoxOption = new JComboBox(searchOptions);
textFieldSearch = new JTextField();
textFieldSearch.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent arg0) {
    try 
        String selected = (String)comboBoxOption.getSelectedItem();
        if(selected.equals("ID"))
            {
                String optionSearch="guest_id";
                System.out.println("baby");
            }else if(selected.equals("First Name"))
            {
                String optionSearch="guest_fname";
            }else if(selected.equals("Middle Name"))
            {
                String optionSearch="guest_mname";
            }else if(selected.equals("Last Name"))
            {
                String optionSearch="guest_lname";
            }else if(selected.equals("Gender"))
            {
                String optionSearch="guest_gender";
            }else if(selected.equals("Date of Birth"))
            {
                String optionSearch="guest_dob";
            }else if(selected.equals("Nationality"))
            {
                String optionSearch="guest_nationality";
                System.out.println(optionSearch);
            }else if(selected.equals("Contact number"))
            {
                String optionSearch="guest_contact";
            }else
            {
                String optionSearch=" ";
            }
           String query="Select * from guest_tbl where '"+optionSearch+"' =? ";
            PreparedStatement pst = conn.prepareStatement(query);
            pst.setString(1, textFieldSearch.getText());
            ResultSet rs =pst.executeQuery();
            tableGuest.setModel(DbUtils.resultSetToTableModel(rs));

这甚至不能编译。你正在声明一个新的"optionSearch"变量在你的if(…)块。

if( something ) {
    String myString = "x";
} 
System.out.println(myString); // This will NOT compile! myString is unknown here

这里的变量"myString"只能从它声明的地方直到右括号处知道。然后它就消失了。所以你要做的就是在每个块中声明一个新变量,然后在块结束后,它就会丢失。在所有的障碍之后,你试图进入它。这行不通。

所以,你应该做的是…

String myString = null; // or whatever default value you want...
if (something) {
    myString = "x";
} else if (something else) {
    myString = "y";
} // etc.
System.out.println(myString); // This will compile and work

在这里,你在开头声明"myString",然后为它设置一些值,当然,然后可以使用它。在你的例子中,你设置它,忘记它,设置它,忘记它,等等——然后尝试使用它。可能你也有一些其他的变量叫做"optionSearch"在某处,否则它不会编译。

(顺便说一句,对于这样的if块,我发现枚举是一种更好地管理它的好方法。为每种可能性声明一个枚举常量,并将所需值存储在一个字段中。但是现在可能有点复杂了

您在if块中声明了字符串optionSearch,因此在此之外不知道。声明并设置字符串optionSearch为if块外部的某个默认值,然后根据条件为其分配不同的值。

String optionSearch = "";
if(selected.equals("ID"))
{
    optionSearch="guest_id";
    System.out.println("baby");
}else if(selected.equals("First Name"))
{
    String optionSearch="guest_fname";
}
....
//prepare statement

最新更新