简体   繁体   中英

JComboBox not populated by database JDBC info - Java

I need to fill a JComboBox with a list of elements from a SQLite Database. At the moment, I don't get data to fill it, but I want to fill it while there's no data to introduce inside the JComboBox, with an element that says that there's no data:

private Connection conn; --> At the beginning of the Java file.

My idea is that if there's no data, just fill the JComboBox with the one element, and if there's data, fill the data and one element more.

The result of this, JComboBox is not filled, with nothing, and error:

database connection closed

What can I do? Thanks you.

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;
}
}

My ConnectDatabase function :

    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;
}

I believe you are missing the line of code

Class.forName("com.mysql.jdbc.Driver");

If that doesn't fix the issue or this is already present, could you provide the method connectDatabase()?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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