java - 通过 Java 中的按钮关闭数据库连接

标签 java database button connection

现在我可以通过单击“连接到数据库”按钮来连接到我的数据库。不幸的是,除了在同一个 if 语句中之外,我无法从其他任何地方关闭数据库。它不将“conn”识别为本地连接变量。我还需要其他按钮来访问“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();
            }
        }
    }
}

具体来说,这是我的 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();
            }
        }
    }

最佳答案

在您的代码中,Connection 对象是一个局部变量,其作用域存在于 if 语句中的 try-catch block 的作用域内。

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

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

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

关于java - 通过 Java 中的按钮关闭数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13043410/

相关文章:

java - 错误: Unresolved compilation problem: RetailItem cannot be resolved to a variable

sql - SQL中多对多的解析

database - Oracle 11g 损坏的物化 View : Stop refresh without dropping view or refreshing view?

sql - 根据每月的日期时间列分隔行

javascript - 单击时反转 html 的颜色(imgs 除外)

java - double 不被减去

java - 在 Java 中查找从一个 URL 到另一个 URL 的相对路径

java - 我的 get 方法不会显示 arraylist 值

android - 音乐停止/开始 onclick 代码仅在第一次时有效,然后并行播放其他轨道

ios - 更换开关的按钮