0
該程序將打開一個對話框,用戶將從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() {
}
}
你能更具體?我把「Connection conn」作爲一個實例變量。現在我只是再次打開從main()的連接?這有什麼不同?或者你是否說我在每種方法中都建立了連接,但是在完成之後在主內部關閉它?我很困惑。 – codefl0w
以爲我非常具體,但是再次在'main()'中打開連接一次,將它用於所需的許多用戶選擇,然後關閉它。這種方法的優點在於,您不必進行不必要的打開和關閉通話,而這些通話都很昂貴。不過,請確保在每次使用它們後立即關閉您的'Statement'和'ResultSet'對象。 –
我的壞男人,我不熟悉繼承,所以我碰到了一個碰撞,當我有想法使用方法,但混淆了什麼將被識別和什麼不會,在方法內。編輯 - 我在每個方法中關閉Statement和ResultSet?不能,我只是關閉一次在Main()的結尾? – codefl0w