我已将combobox
链接到MySQL数据库,以便按员工的姓名和姓氏显示其雇员列表。
问题是,当我单击某个雇员时,我想在单独的Textfield
中显示其注册号。
我尝试使用此代码,但不幸的是,它不起作用:
public void popcombo(){
try {
String sql ="Select registration,surname,name from employee";
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();
while(rs.next()){
String surname = rs.getString("surname");
String registration = rs.getString("registration");
String name =rs.getString("name");
StringBuilder st = new StringBuilder();
st.append(surname).append(" ").append(name);
AutoCompleteDecorator.decorate(empcombo);
empcombo.addItem(st);
}
} catch(Exception ty)
{
JOptionPane.showMessageDialog(null,ty);
}
}
private void empcomboItemStateChanged(java.awt.event.ItemEvent evt) {
String p= empcombo.getSelectedItem().toString();
try{
String sql ="Select surname,name,registration from employee where registration='"+p+"'";
rs=ps.executeQuery();
while(rs.next()){
jTextField1.setText(rs.getString("registration"));
}
}catch(Exception tz)
{
JOptionPane.showMessageDialog(null,tz);
}
}
最佳答案
我用这段代码:
private void empcomboItemStateChanged(java.awt.event.ItemEvent evt) {
try{
{
String selectedItem = empcombo.getSelectedItem().toString();
String sql ="Select registration from employee where surname='"+selectedItem.split(" ")[0]+"' and name='"+selectedItem.split(" ")[1]+"'";
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();
if(rs.next()){
jTextField1.setText(rs.getString("registration"));
}
}
}catch(Exception gh){
JOptionPane.showMessageDialog(null, gh);
}
}