I am working on a simple application that includes a JComboBox for users to select from. I am new to Java and am having trouble populating the JComboBox with results from an SQL select statement. This is due to my lack of knowledge!
I have written 3 classes, a dbConnection class to handle the db side of things. Another class that instantiates my GUI, and the last class contains my main method:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
// Extends java.sql :~ describes connections to Oracle db
class dbConn {
Connection conn;
Statement stmt;
ResultSet rs;
String conString;
String sqlString;
void dbConn() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(conString);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
if (conn != null) {
System.out.println("Connection established, database uplink is online.");
} else {
System.out.println("Connection failed, please check database status.");
}
}
}
Second class for the GUI:
import javax.swing.*;
public class CaseMoverUI {
void testUI(){
// Create a new JFrame container
JFrame jfrm = new JFrame("CaseMover");
jfrm.setSize(550, 450);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox jbox = new JComboBox();
jfrm.add(jbox);
jfrm.setVisible(true);
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new CaseMoverUI();
}
});
}
}
And lastly:
public class sqlCaller {
public static void main(String args[]){
//instantiate db object and pass values to the constructor
dbConn db = new dbConn();
db.conString = "jdbc:oracle:thin:system/password123@127.0.0.1:1521:xe";
db.sqlString = "SELECT true FROM dual";
db.dbConn();
CaseMoverUI ui = new CaseMoverUI();
ui.testUI();
}
}
The first thing I am not sure how to do is to retrieve my results and add them to the JComboBox. I know I need to write a method for the dbConn class, and pass an SQL query to it.
Using the HR test schema with Oracle XE, SQL query might be something like:
SELECT first_name FROM employees;
I'm not sure of the proper way to write this method however. Any help here would be much appreciated!