This program is going to open a dialog box from where the user will make a selection from 7 choices. Depending on the choice selected, I am going to use SQL statements to extract the data from the DataBase and print the it onto the screen.
What I am wondering is, I want to do these steps each in their own methods, and just call them from main() rather than have a very LARGE Switch statement. I cant seem to figure out how to do this WITHOUT having to make a connection for EVERY method.
import javax.swing.*;
import java.sql.*;
public class PC_05__PopulationDatabase {
public static void main(String[] args) throws SQLException {
final String DB_URL = "jdbc:derby:CityDB";
// List of actions
String[] arr = new String[7];
arr[0] = "1) Sort Cities by Population - ASCENDING ORDER";
arr[1] = "2) Sort Cities by Population - DESCENDING ORDER";
arr[2] = "3) Sort Cities by Name";
arr[3] = "4) Get Total Population of ALL Cities";
arr[4] = "5) Get Average Population of ALL Cities";
arr[5] = "6) Get Highest Population";
arr[6] = "7) Get Lowest Population";
try {
// Open Connection
Connection conn = DriverManager.getConnection(DB_URL);
System.out.println("Connection created to Population Database.");
// Statement and Result
Statement stmt = conn.createStatement();
String sqlStatement;
ResultSet result;
// Selection dialog
Object userAction = JOptionPane.showInputDialog(null, "Select an action: ", "Actions", JOptionPane.PLAIN_MESSAGE, null, arr, null);
String selection = userAction.toString();
int choice = Integer.parseInt(selection);
// Selection Actions
switch(choice) {
case 0:
break;
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
}
sqlStatement = "SELECT Description FROM Coffee";
result = stmt.executeQuery(sqlStatement);
// Close Connection
conn.close();
System.out.println("Connection closed.");
}
catch(Exception ex) {
System.out.println("ERROR: " + ex.getMessage());
}
}
public static void sortPopAscending() {
}
public static void sortPopDescending() {
}
public static void sortName() {
}
public static void totalPop() {
}
public static void avgPop() {
}
public static void highestPop() {
}
public static void lowestPop() {
}
}