我想通过MySQL使用ComboBox上的选定值获取数据。但是,在JList中,它显示songpick
列中的所有数据,而不从ComboBox获取值。我的sql命令有什么问题吗?
FillCombo()
方法:
PreparedStatement st = con.prepareStatement("select * from customer");
ResultSet rs = st.executeQuery();
while(rs.next()){
String CustomerName= rs.getString("customername");
jComboBox1.addItem(CustomerName);
}
FillList()
方法:
DefaultListModel dlm = new DefaultListModel();
PreparedStatement st = con.prepareStatement("select songpick from customer");
ResultSet rs = st.executeQuery();
if(rs.next()){
String songpick=rs.getString("songpick");
dlm.addElement(songpick);
jList1.setModel(dlm);
}
答案 0 :(得分:2)
如果您按照客户的名称从数据库中过滤结果集会很有帮助,例如......
DefaultListModel dlm = new DefaultListModel();
try (PreparedStatement st = con.prepareStatement("select songpick from customer where customername=?")) {
String customerName = (String)jComboBox1.getSelectedItem();
st.setString(1, customerName);
try (ResultSet rs = st.executeQuery()) {
if (rs.next()) {
String songpick = rs.getString("songpick");
dlm.addElement(songpick);
}
jList1.setModel(dlm);
}
} catch (SQLException exp) {
exp.printStackTrace();
}
ps:我不了解你的数据库结构,所以我只是猜测关系
您还应该查看The try-with-resources Statement,了解有关如何管理资源的详细信息以及SQL Where Clause
答案 1 :(得分:1)
您需要有一个WHERE
子句并设置您想要的值
E.g。 SELECT songpick FROM customer WHERE <columnName> = ?
并使用executeQuery
st.setString(1, "Foo");
语句之前所需的值