简体   繁体   English

来自MySQL数据库的数据JList和ComboBox

[英]Data JList and ComboBox from mysql database

I would to get data from selected value on the ComboBox by using MySQL. 我将使用MySQL从ComboBox上的选定值中获取数据。 However, in the JList, it shows all the data form songpick column without get the value from the ComboBox. 但是,在JList中,它显示了songpick列中的所有数据,而没有从ComboBox中获取值。 Is there anything wrong with my sql command? 我的sql命令有什么问题吗?

FillCombo() method: FillCombo()方法:

        PreparedStatement st = con.prepareStatement("select * from customer");
        ResultSet rs = st.executeQuery();
        while(rs.next()){
            String CustomerName= rs.getString("customername");
            jComboBox1.addItem(CustomerName);
        }

FillList() method: 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);
        }

It would be helpful if your filtered the result set from the database by the customer's name, for example... 如果您用客户的名字从数据库中过滤了结果集,这将很有帮助,例如...

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: I don't know you database structure, so I'm only guessing at the relationships ps:我不知道您的数据库结构,所以我只是在猜测关系

You should also take a look at The try-with-resources Statement for more details about how to manage your resources and the SQL Where Clause 您还应该查看try-with-resources语句,以获取有关如何管理资源和SQL Where子句的更多详细信息。

You need to have a WHERE clause and set the value that you want to get from 您需要具有WHERE子句并设置要从中获取的值

Eg SELECT songpick FROM customer WHERE <columnName> = ? 例如SELECT songpick FROM customer WHERE <columnName> = ? and set the value of the that you need before the executeQuery statement with st.setString(1, "Foo"); 并使用st.setString(1, "Foo");executeQuery语句之前设置所需的值st.setString(1, "Foo");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM