该程序将打开一个对话框,用户可从中选择7个选项。根据所选的选项,我将使用SQL语句从DataBase中提取数据并将其打印到屏幕上。
我想知道的是,我想在他们自己的方法中执行这些步骤,只需从main()调用它们,而不是使用非常大的Switch语句。我似乎无法弄清楚如何做到这一点,不必为每个方法建立连接。
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() {
}
}
答案 0 :(得分:1)
以下是我解决类似问题的方法:
Connection conn
设为您班级的实例变量。不要让它static
,或者如果你需要多个同时连接,你就会自己踢。switch
语句,匿名类等。