我需要用 SQLite 数据库中的元素列表填充 JComboBox。目前,我没有获取数据来填充它,但我想在 JComboBox 内部没有数据可引入的情况下填充它,并使用一个表示没有数据的元素:
私有(private)连接conn; --> 在 Java 文件的开头。
我的想法是,如果没有数据,就用一个元素填充 JComboBox,如果有数据,则再填充数据和一个元素。
这样做的结果,JComboBox没有被填充,什么都没有,并且报错:
database connection closed
我能做什么?谢谢你。
private boolean cargarListasConfiguraciones() {
String sql = "SELECT * FROM "+table_name;
if (conn == null) {
conn = this.connectDatabase();
}
try (
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)){
if (rs.first() == false) {
this.cbConfigsSelector.addItem("<Without data>");
this.cbConfigsSelector.setSelectedItem("<Without data>");
this.cbConfigsSelector.setEnabled(false);
return true;
} else {
this.cbConfigsSelector.addItem("<No one selected>");
this.cbConfigsSelector.setSelectedItem("<No one selected>");
while (rs.next()) {
this.cbConfigsSelector.addItem(rs.getString("config_name"));
}
return true;
}
} catch (SQLException e) {
System.out.println(e.getMessage());
return false;
}
}
我的ConnectDatabase 函数:
private Connection connectDatabase() {
String JDBC_url = "jdbc:sqlite:C:/Users/Multimedia/eclipse-workspace/Automatizador-MQS-Productos/sqls/mqs_providers_configs.sqlite";
if (conn != null) {
return conn;
}
conn = null;
try {
conn = DriverManager.getConnection(JDBC_url);
System.out.println("Connected");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("Error accesing database");
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
return conn;
}
最佳答案
我相信你错过了这行代码
Class.forName("com.mysql.jdbc.Driver");
如果这不能解决问题或者问题已经存在,您能否提供 connectDatabase() 方法?
关于java - JComboBox 未填充数据库 JDBC 信息 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58938894/