[英]Populate JComboBox with data from MySQL
我有一个名为“供应商”的表,它有两列“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 语句,然后将其存储在字符串中,但是当我插入数据时,我将不断地添加更多字符串以容纳额外的信息。
我不知道您是如何创建 combobox 的,因为您忽略了发布代码,但简而言之,要在每次添加新供应商时更新 combobox,您可以使用以下逻辑(实际实施取决于您):
在您的 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
的 model ,显然,供应商的名称是从存储您要添加的新供应商名称的任何变量中获得的。
如果异常阻止添加供应商,则将供应商名称添加到 combobox 的部分将不会运行,因为控制会立即传递到 try/catch 的catch
部分。
当您已经拥有所需的所有数据时,在成功插入新供应商后,运行无关的 select 语句来重新填充 combobox 是没有意义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.