首页 > 解决方案 > 使用来自 MySQL 的数据填充 JComboBox

问题描述

我有一个名为“供应商”的表,它有两列“suppID”和“suppName”。

我想从 suppName 中提取数据并将其填充到 JComboBox 中,以使内容保持最新,这意味着如果插入或删除了新行,JComboBox 将完全按照它存储在表中的数据显示打开它的时间

        addStock.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent ae) {
            int result = JOptionPane.showConfirmDialog(null,addStockPanel,"Add new stock", JOptionPane.OK_CANCEL_OPTION);
            try{
                //Connect to DB
                Connection conn = CatalogueDB.getConnection();
                //Prepare statement to pull data
                Statement pull = conn.createStatement();


            } catch(Exception e){System.out.println("Error adding supplier");}
            //Finish by printing a message to say the insert has worked.
            finally{
                System.out.println("Insert Completed.");

以我的知识水平想到的唯一想法是从表中执行一个 select 语句,然后将其存储在一个字符串中,但是当我插入数据时,我将不断地添加更多字符串以容纳额外的信息。

标签: javamysqlswingjdbc

解决方案


我不知道您是如何创建组合框的,因为您忽略了发布代码,但简而言之,要在每次添加新供应商时更新组合框,您可以使用以下逻辑(实际实现取决于您):

在您的 try 语句中(您实际上是在尝试将新供应商添加到您的表中),遵循 SQL 语句的执行,如下所示:

try
{
    //Connect to DB
    Connection conn = CatalogueDB.getConnection();
    //Prepare statement to push new supplier data
    Statement push = conn.createStatement();

    // adds new supplier name
    model.addElement(<name of supplier>);
    // notifies combobox that the underlying model has changed
    // box will be repainted automatically
    model.fireContentsChanged();
}
catch(Exception e)
{
    e.printStackTrace();
    // other handling as necessary
}

model用于您的模型在哪里JComboBox,显然,供应商的名称是从存储您尝试添加的新供应商名称的任何变量中获得的。

如果异常阻止添加供应商,则将供应商名称添加到组合框中的部分将不会运行,因为控制会立即传递到catch您的 try/catch 部分。

当您已经拥有所需的所有数据时,在成功插入新供应商后运行无关的选择语句来重新填充组合框是没有意义的。


推荐阅读