0

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;
}
juannmcc
  • 109
  • 1
  • 1
  • 12

1 Answers1

1

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()?

danelliott
  • 150
  • 1
  • 7
  • added function, where i got to put that Class.forName, which utility gives on this case? I didnt know about it – juannmcc Nov 19 '19 at 17:00
  • I would put it as the first line of code within the try statement in connectDatabase(). If you want to learn more about what this does, you can go [here.](https://stackoverflow.com/questions/8053095/what-is-the-actual-use-of-class-fornameoracle-jdbc-driver-oracledriver-while) – danelliott Nov 19 '19 at 17:05