title: Closing a database connection from a button in Java
body: <p>Right now I can connect to my database by clicking the connect to database button. Unfortunately I can't close the database from anywhere else but within that same if statement. It doesn't recognize "conn" as a local Connection variable. I also need other button to access "conn" to perform other tasks, so this one hurdle is holding back multiple fronts. Below is my code:</p>
  
  <pre><code>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();
              }
          }
      }
  }
  </code></pre>
  
  <p>Specifically this is my actionEventPerformed sequence that is failing due to an error at "conn.close();"</p>
  
  <pre><code>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();
              }
          }
      }
  </code></pre>