0

現在、[データベースに接続] ボタンをクリックしてデータベースに接続できます。残念ながら、他のどこからでもデータベースを閉じることはできませんが、同じ if ステートメント内ではできません。「conn」をローカル接続変数として認識しません。他のタスクを実行するために「conn」にアクセスするための他のボタンも必要です。そのため、この 1 つのハードルが複数のフロントを妨げています。以下は私のコードです:

import java.awt.*;
import java.awt.event.*;
import java.sql.*;

import javax.swing.*;


public class ConnectToDB implements ActionListener {

    final String url = "jdbc:mysql://localhost/";
    final String dbName = "project3";
    final String DBdriver = "com.mysql.jdbc.Driver";
    final String userName = "root"; 
    final String password = "OMGnpw=-0";

    //GUI STUFF
    //constants
    final int windowX = 640; //pixels
    final int windowY = 655; //pixels
    final int fieldX = 20;   //characters

    //window
    JFrame window = new JFrame("Mike's MySQL GUI Client");

    //Connection Details
    JLabel enterInfo = new JLabel("Enter Connection Details: ");
    JLabel driver = new JLabel("Database Driver: ");
    JTextField driverText = new JTextField(fieldX);
    JLabel dburl = new JLabel("Database URL: ");
    JTextField dburlText = new JTextField(fieldX);
    JLabel dbuser = new JLabel("Username: ");
    JTextField dbuserText = new JTextField(fieldX);
    JLabel dbpass = new JLabel("Password: ");
    JTextField dbpassText = new JTextField(fieldX);

    //Enter a SQL Command
    JLabel enterSQL = new JLabel("Enter a SQL Command:");
    JTextArea enterSQLText = new JTextArea(10, 30);

    //Connection Status and Command Buttons
    JLabel connectionStatus = new JLabel ("No Connection Now");
    JButton connectButton = new JButton("Connect");
    JButton executeButton = new JButton("Execute SQL Command");
    JButton clearCommandButton = new JButton("Clear Command");

    //SQL Execution Result
    JLabel executionResult = new JLabel("SQL Execution Result:");
    JButton clearResultsButton = new JButton("Clear Results");
    JTextArea executionResultText = new JTextArea(20, 50);

    public ConnectToDB() throws Exception{

        //Configure GUI
        window.setSize(windowX, windowY);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        driverText.setEditable(false);
        dburlText.setEditable(false);
        dbuserText.setEditable(false);
        dbpassText.setEditable(false);
        executionResultText.setEditable(false);

        //Register Event Listeners
        connectButton.addActionListener(this);
        executeButton.addActionListener(this);
        clearCommandButton.addActionListener(this);
        clearResultsButton.addActionListener(this);

        //Construct Container
        Container c = window.getContentPane();
        final BoxLayout LAYOUT_STYLE = new BoxLayout(c, BoxLayout.Y_AXIS);
        JPanel panel1 = new JPanel();
        panel1.setLayout(new FlowLayout());
        JPanel panel2 = new JPanel();
        panel1.setLayout(new FlowLayout());
        JPanel panel3 = new JPanel();
        panel1.setLayout(new FlowLayout());
        JPanel panel4 = new JPanel();
        panel1.setLayout(new FlowLayout());
        JPanel panel5 = new JPanel();
        panel1.setLayout(new FlowLayout());
        JPanel panel6 = new JPanel();
        panel1.setLayout(new FlowLayout());
        JPanel panel7 = new JPanel();
        panel1.setLayout(new FlowLayout());
        JPanel panel8 = new JPanel();
        panel1.setLayout(new FlowLayout());

        driverText.setText(DBdriver);
        dburlText.setText(url);
        dbuserText.setText(userName);
        dbpassText.setText(password);

        c.setLayout(LAYOUT_STYLE);

        panel5.add(enterInfo);
        panel1.add(driver);
        panel1.add(driverText);
        panel2.add(dburl);
        panel2.add(dburlText);
        panel3.add(dbuser);
        panel3.add(dbuserText);
        panel4.add(dbpass);
        panel4.add(dbpassText);
        panel5.add(connectionStatus);
        panel5.add(connectButton);
        panel6.add(enterSQL);
        panel6.add(enterSQLText);
        panel7.add(executeButton);
        panel7.add(clearCommandButton);
        panel8.add(executionResult);
        panel8.add(clearResultsButton);
        panel8.add(executionResultText);
        c.add(panel5);
        c.add(panel1);
        c.add(panel2);
        c.add(panel3);
        c.add(panel4);
        c.add(panel6);
        c.add(panel7);
        c.add(panel8);

        window.setVisible(true);//END GUI STUFF
    }

    public static void main(String[] args) throws Exception{
        @SuppressWarnings("unused")
        ConnectToDB gui = new ConnectToDB();
    }

    public void actionPerformed(ActionEvent e){
        if (e.getSource() == connectButton){
            try 
            {
                //DB Connection details
                System.out.println("Attempting to connect to database...");
                //Connect to DB and notify user
                Class.forName(DBdriver).newInstance();
                Connection conn = DriverManager.getConnection(url+dbName,userName,password);
                System.out.println("Connected to the database");

            } 
            catch (Exception f) {
            f.printStackTrace();
            }
        }
        else {
            try{

                conn.close();
                System.out.println("Disconnected from database");
                System.out.println("Other Button Works!");
            }
            catch (Exception g){
                g.printStackTrace();
            }
        }
    }
}

具体的には、これは「conn.close();」でのエラーが原因で失敗している私の actionEventPerformed シーケンスです。

public void actionPerformed(ActionEvent e){
        if (e.getSource() == connectButton){
            try 
            {
                //DB Connection details
                System.out.println("Attempting to connect to database...");
                //Connect to DB and notify user
                Class.forName(DBdriver).newInstance();
                Connection conn = DriverManager.getConnection(url+dbName,userName,password);
                System.out.println("Connected to the database");

            } 
            catch (Exception f) {
            f.printStackTrace();
            }
        }
        else {
            try{

                conn.close();
                System.out.println("Disconnected from database");
                System.out.println("Other Button Works!");
            }
            catch (Exception g){
                g.printStackTrace();
            }
        }
    }
4

1 に答える 1

5

コードでは、Connectionオブジェクトは、if ステートメントの try-catch ブロックのスコープ内にスコープが存在するローカル変数です。

グローバル変数を作成し、ボタンを使用して接続を初期化/開いたり閉じたりしてみてください。次のことをお勧めします。

  • 接続オブジェクトを格納するためのグローバル変数を作成します
  • 接続を開く/閉じるためのメソッドを作成getConnection()しますcloseConnection()
  • イベント処理コードから、これらの関数のいずれかを呼び出して接続を処理します。

これは、接続処理が UI コンポーネントと結合されなくなるため、接続を処理するためのより良い方法です。

于 2012-10-24T05:21:48.930 に答える