我的问题类似于this question,但对我不起作用=(
我有一个名为客户的数据库,其中包含ID,姓名,电话和电子邮件。当我注册客户端时,他的名字和ID显示在Jlist上。现在我想点击Jlist中的名称并“搜索”该客户端的所有数据(ID,名称,电话和电子邮件)。 我已经有textField来链接数据,但是没有工作......
我做了什么:
DefaultListModel model = new DefaultListModel();
client_listClientes.setModel(model);
try {
String host = "jdbc:derby://localhost:1527/ANAIA_DB";
String uName = "*****";
String uPass = "*****";
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement();
String sql = "SELECT * FROM APP.CLIENTS";
int id_col = rs.getInt("clientID"); // I need to make this work.. when i select a value, it gives me the id for that client
ResultSet RS = stmt.executeQuery("SELECT * FROM APP.CLIENTS WHERE CLIENTID='"+id_col+"'");
rs = stmt.executeQuery(sql);
while (RS.next()){
String name = rs.getString("clientName");
client_textName.setText(name);
String phone = rs.getString("clientPhone");
client_textPhone.setText(phone);
String email = rs.getString("clientMail");
client_textMail.setText(email);
}
}
catch (SQLException err) {
JOptionPane.showMessageDialog(main.this, err.getMessage());
}
我读到我必须使用一个监听器,但我尝试了另一个问题的例子并且没有工作= /
答案 0 :(得分:1)
只需将所有数据一次加载到Client
对象中,而不是每次都尝试返回并点击数据库。
class Client {
int id;
String name;
String phone;
String email;
// getter and setters
@Override
public String toString() {
return id + " : " + name;
}
}
然后,您可以将所有数据加载到客户端对象中,然后将它们添加到模型中
ResultSet RS = stmt.executeQuery("SELECT * FROM APP.CLIENTS");
...
while (RS.next()){
Client client = new Client();
client.setId(rs.getInt("id");
client.setName(rs.getString("clientName"));
client.setPhone(rs.getString("clientPhone"));
client.setEmail(rs.getString("clientMail");
model.addElement(client);
}
然后,当您单击JList时,只需提取所选的Client
对象并使用getters
设置文本字段
client_listClientes.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
JList list = (JList)e.getSource();
Client client = (Client)list.getSelectedValue();
textfield.setText(client.getEmail());
}
}
});