有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java根据另一个JCombobox填充JCombobox值

我有两个JComboxA和B,所以如果我从A表中选择任何项目,那么与A中选择的项目相关的值应该填入JComboxB。我尝试了这个方法,但得到了一个错误:

java.lang.ArrayIndexOutOfBoundsException: 0

pst.setString(1, client.getSelectedItem().toString());

try
{
    String query="select `User_Name` from Client where `Client_Name`='?' ";
    PreparedStatement pst=conn.prepareStatement(query);
    pst.setString(1, client.getSelectedItem().toString());

    ResultSet rs=pst.executeQuery();

    user.addItem("--Select--");
    while(rs.next())
    {
        user.addItem(rs.getString("User_Name"));            
    }
//      return;
    System.out.println(query);

}
catch(Exception g)
{
    g.printStackTrace();
}

共 (2) 个答案

  1. # 1 楼答案

    你犯了个错误

    不需要使用“?”,应该是Client_Name=

  2. # 2 楼答案

    使用setString()时,preparedstatement负责引用参数

    试试看

    String query="select User_Name from Client where Client_Name = ?";
    PreparedStatement pst=conn.prepareStatement(query); 
    pst.setString(1, String.valueOf(client.getSelectedItem()));
    

    我猜当您使用'?'时,准备好的语句不会将其作为参数,这就是为什么您会得到IndexOutOfBounce