我已将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);
}
}
答案 0 :(得分:0)
empcomboItemStateChanged()
,未在第二种方法中调用ps=conn.prepareStatement(sql);
而where registration='"+p+"'";
错误。
在第一种方法中,不需要列registration
comboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
{//Now we will get only selected item
String selectedValue = comboBox.getSelectedValue().toString();
String values[]=selectedValue.split("\\s+");
String sql ="Select registration from employee where surname='"+values[0]+"' and name='"+values[1]+"'";
//since st.append(surname).append(" ").append(name);, double space between surname and name
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();
if(rs.next()){
jTextField1.setText(rs.getString("registration"));
}
}
}
});
答案 1 :(得分:0)
我使用了这段代码:
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);
}
}
答案 2 :(得分:0)
最后我得到了答案,特别感谢Satya帮助我。这是最终的代码:
private void empcomboItemStateChanged(java.awt.event.ItemEvent evt) {
try{
String selectedItem = empcombo.getSelectedItem().toString();
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"));
} }
}catch(Exception gh){
JOptionPane.showMessageDialog(null, gh);
}
}