我有这段代码:
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错误,我不知道如何解决它
答案 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"));
}
}