split()Arrayindexoutofbound sql

时间:2015-07-26 19:13:40

标签: java mysql sql split

我有这段代码:

     private void empcomboItemStateChanged(java.awt.event.ItemEvent evt) {                                          

    try{
    {
        String selectedItem = empcombo.getSelectedItem().toString();

        String sql ="Select matricule from employés where nom='"+selectedItem.split(" ")[0]+"' and prénom='"+selectedItem.split(" ")[1]+"'";

        ps=conn.prepareStatement(sql); 
        rs=ps.executeQuery();              
        if(rs.next()){
            jTextField1.setText(rs.getString("matricule"));

        } 
    }
}catch(Exception gh){
    JOptionPane.showMessageDialog(null, gh);
}
}       

它不断返回Arrayindexoutofbound错误,我不知道如何解决它

1 个答案:

答案 0 :(得分:1)

您必须确保selectedItem中至少包含2个由space分隔的元素。所以首先检查它的长度。

  String[] items = selectedItem.split(" ");
  if(items.length >= 2){
    String sql ="Select matricule from employés where nom='"+items[0]+"' and prénom='"+items[1]+"'";
    ps=conn.prepareStatement(sql); 
    rs=ps.executeQuery();              
    if(rs.next()){
        jTextField1.setText(rs.getString("matricule"));
    } 
  }