从Java中的按钮关闭数据库连接

Pee*_*ure 0 java database connection button

现在我可以通过单击connect to database按钮连接到我的数据库.不幸的是,我不能从其他任何地方关闭数据库,但在同一个if语句中.它不会将"conn"识别为本地Connection变量.我还需要其他按钮来访问"conn"来执行其他任务,所以这一个障碍阻碍了多个战线.以下是我的代码:

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();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

具体来说,这是我的actionEventPerformed序列因"conn.close();"错误而失败

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();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Suj*_*jay 5

在您的代码中,Connection对象是一个局部变量,其范围存在于if语句的try-catch块的范围内.

尝试创建全局变量并使用按钮初始化/打开和关闭连接.我建议如下:

  • 创建一个用于存储连接对象的全局变量
  • 创建getConnection()closeConnection()打开/关闭连接的方法
  • 从事件处理代码中,调用其中一个函数来处理连接.

这是处理连接的更好方法,因为连接处理将不再与您的UI组件耦合.