如何使用方法执行以下操作?

时间:2013-12-09 03:03:17

标签: java database methods static-methods derby

该程序将打开一个对话框,用户可从中选择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() {

}

}

1 个答案:

答案 0 :(得分:1)

以下是我解决类似问题的方法:

  • Connection conn设为您班级的实例变量。不要让它static,或者如果你需要多个同时连接,你就会自己踢。
  • 打开数据库连接
  • 虽然您希望用户执行操作:让用户进行选择,然后调用一个单独的函数,该函数具有适合该选择的SQL。你将需要一些东西来理清要调用的函数,无论是switch语句,匿名类等。
  • 关闭数据库连接