satnam
satnam

Reputation: 1425

Java - Populate a JCombobox with SQLite database

I want to populate a JComboBox with a database column (SQLite).

My database connection is setup through a class called DatabaseConnection setup in anther package.

Here is how it looks like

import java.sql.*;

import javax.swing.JOptionPane;

public class DatabaseConnection {
Connection conn = null;

public static Connection ConnectDB() {

    try {
        Class.forName("org.sqlite.JDBC");
        Connection conn = DriverManager.getConnection("jdbc:sqlite:database.db");
        JOptionPane.showMessageDialog(null, "Connection Established");
        conn.setAutoCommit(false);
        return conn;
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
        return null;
    }
}
}

In my JFrame class I am creating following method, which according to a youtube tutorial should work

public void PopulateJCB()
{
    String queryString = "SELECT DISTINCT [Account Name] FROM main ORDER BY [Account Name]";
    try
    {
        Connection statJCBaccountname = DatabaseConnection.ConnectDB();
        Statement stmt = statJCBaccountname.createStatement();
        ResultSet rsJCBaccountname = stmt.executeQuery(queryString);

        while (rsJCBaccountname.next())
        {
            comboAccountName.addItem(rsJCBaccountname.getString(1));
        }

    catch (SQLException e)
    {
        e.printStackTrace();
    }

}

But it displays following errors at "comboAccountName.addItem(rsJCBaccountname.getString(1));"

Multiple markers at this line
- Type safety: The method addItem(Object) belongs to the raw type JComboBox. References to generic type JComboBox<E> should be 
 parameterized
- comboAccountName cannot be resolved

Please help!

Upvotes: 0

Views: 714

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347204

I'm not really sure what you're expecting...

  • statJCBaccountname isn't even in the code example you've provided, but the compiler is saying that the variable is undefined
  • There is no such method as createStatement in the DatabaseConnection class

You need to resolve these issues before the program will compile. I'd suggest staying away from YouTube tutorials unless you know the author.

Take a look at JDBC Database Access for more details...

Upvotes: 1

Related Questions