gpt4 book ai didi

java - 如何在 JComboBox 中填充数据?

转载 作者:行者123 更新时间:2023-11-29 10:14:15 26 4
gpt4 key购买 nike

我已经创建了一个 GUI,并且有一个位于外部的数据库,我可以从中获取数据。我正在使用 NetBeans 中的 GUI 生成器来执行此操作。有谁知道用来自数据库的值填充 jComboBox 的简单方法?当我运行该项目时,没有任何错误,但组合框仍为空。

这是设置带有折扣名称的组合框的代码:

public void setDiscountNames(String type, JComboBox cbox) {        
cbox.removeAllItems();
ArrayList<Discount> names = new ArrayList<Discount>();
try {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/abpp034?user=abpp034&password=120001772");
stmt = con.prepareStatement("SELECT Name FROM Discount WHERE Type = \"" + type + "\"");
rs = stmt.executeQuery();

while(rs.next()){
cbox.addItem(rs.getString("Name"));
}
} catch (SQLException ex) {
Logger.getLogger(Model.class.getName()).log(Level.SEVERE, null, ex);
}
}

它位于与 jComboBox 对象不同的类中。这个类称为模型。

这是我在名为 DiscountGUIView 的表单中调用 setDiscountNames 方法的地方:

private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt){                                           
model.setDiscountNames("Fixed", jComboBox1);
}

好的(更新)查询确实打印了结果:

run:

旅行标准固定标准构建成功(总时间:1 秒)

最佳答案

可能是您的 SELECT 查询未返回任何结果。要验证这一点,您可以在 while (rs.next()) 循环中添加日志记录语句。我的 SQL 知识有点生疏,但我记得对字符串文字使用 '(单引号),而您在语句中使用 "(双引号)。

除此之外,我看到了一些可能导致问题的事情:

  • PreparedStatement 的 SQL 代码不应通过字符串连接创建。相反,使用 ? 作为将被替换到语句中的参数值,例如

    stmt = con.prepareStatement("SELECT Name FROM Discount WHERE Type = ?");
    stmt.setString(1, type); // first (and only) parameter
    rs = stmt.executeQuery();
  • 强烈建议您在使用完 JDBC 资源后显式关闭它们。为此,您需要在 catch (SQLException ...) 之后添加一个 finally block ,例如

    } finally {
    try {
    if (rs != null) rs.close();
    } catch (SQLException ignore) {}

    try {
    if (stmt != null) stmt.close();
    } catch (SQLException ignore) {}

    try {
    if (conn != null) conn.close();
    } catch (SQLException ignore) {}
    }

    或者,最好使用 try-with-resources 语句(如果您使用的是 Java 7 及更高版本):

    try (Connection con = DriverManager.getConnection(...)) {
    // ...
    try (PreparedStatement stmt = con.prepareStatement("SELECT Name FROM Discount WHERE Type = ?")) {
    // ...
    try (ResultSet rs = stmt.executeQuery()) {
    while (rs.next()) {
    // processing
    }
    }
    }
    } catch (SQLException) {
    Logger....;
    } // notice no finally block; resources are closed automatically

关于java - 如何在 JComboBox 中填充数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22519982/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com