jComboBox1.setModel(customers);
public class CustomerData {
private static final String JDBC_CONNECTION_URL = "jdbc:mysql://localhost/test";
private static final String DATABASE_USER = "root";
private static final String DATABASE_PASSWORD = "root";
// query to select customer data
private static final String SQL_FETCH_CUSTOMERS = "SELECT custName FROM customers";
private Connection connection = null;
public CustomerData(){
initConnection();
}
private void initConnection() {
try {
//load the mysql driver
Class.forName("com.mysql.jdbc.Driver");
//create the database connection
connection = DriverManager.getConnection(JDBC_CONNECTION_URL, DATABASE_USER, DATABASE_PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void closeConnection(){
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
connection = null;
}
}
}
public ArrayList fetchCustomerData(){
if (connection != null){
Statement statement = null;
try {
statement = connection.createStatement();
//get results from database
ResultSet resultSet = statement.executeQuery(SQL_FETCH_CUSTOMERS);
//get customers from resultset and return them to the app
return convertResultSetToCustomersArray(resultSet);
} catch (SQLException e) {
e.printStackTrace();
} finally {
//close the statement we just used
if (statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}else{
System.out.println("NO VALID DATABASE CONNECTION, CAN'T FETCH CUSTOMER DATA!");
}
return new ArrayList();
}
private ArrayList convertResultSetToCustomersArray(ResultSet results) throws SQLException{
ArrayList customers = new ArrayList();
//loop the results and add customers to an ArrayList
while (results.next()){
customers.add(results.getString("custName"));
}
return customers;
}
private String[] customers = null;
private void initData(){
CustomerData customerData = new CustomerData();
ArrayList custArrayList = customerData.fetchCustomerData();
//get the array from the ArrayList and cast it to a String[]
customers = (String[]) custArrayList.toArray(new String[0]);
}
}