Hi there, I'm looking for a way to add content to a JComboBox from a database. I have the code to connect the database to my application working fine but am struggling to find the appropriate way to make my JComboBox display data from my database. I'll leave all the code I have at present...
import java.sql.*;
import java.io.IOException;
import java.io.*;
import java.util.Properties;
public class ConnectDB {
public static void init(String fileName)
throws IOException, ClassNotFoundException
{
Properties props = new Properties();
FileInputStream in = new FileInputStream(fileName);
props.load(in);
String driver = props.getProperty("jdbc.driver");
url = props.getProperty("jdbc.url");
username = props.getProperty("jdbc.username");
password = props.getProperty("jdbc.password");
Class.forName(driver);
}
public static Connection getConnection() throws SQLException
{
return DriverManager.getConnection(url,username,password);
}
private static String url;
private static String username;
private static String password;
}
(I obviously have a text file in my folder with my connection details)
Then I'm trying to build a GUI in netbeans that will retrieve and update my database so I have something like this...
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1.addItem("Please Click Button");
try{
ConnectDB myDB = new ConnectDB();
myDB.init("DBoracle.txt");
Connection conn = null;
conn = myDB.getConnection();
String query = "select * from Employee";
Statement stmt = null;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
rs.next();
String s = rs.getString(2);
//Return the second entry from my database and add it to my JComboBox
// in theory i'll be adding a loop later to add all the entries to my JComboBox
jComboBox.setItem(s);
}
catch(Exception e){}
}