简体   繁体   中英

JDBC closing a database connection

I'm not sure how to close the database through this method of database connection, it's opens and connects successfully, I don't know if it closes when I close the GUI it's coded to

 import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Statement;

    import javax.swing.JOptionPane;

    public class Database_link  {
        Connection connect = null;
        Statement state = null;
        public static Connection dbConnector()
        {
            try{
                Class.forName("org.hsqldb.jdbcDriver");
                Connection connect = DriverManager.getConnection("jdbc:hsqldb:file:C:\\Users\\Backup\\Documents\\Eclipse\\Eclipse Kelper\\com1028_workspace\\tf00082_prototype\\hsqldb\\AppDB;ifexists=true;shutdown=true",
                                    "adminTom", "password");
                JOptionPane.showMessageDialog(null, "Connection Successful");
                return connect;

                }
            catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "Failed Connection");
                    return null;
                }
            }

    }

If the GUI being closed terminates the program, yes it would close the database otherwise it would stay open. To close your database you would use:

connect.close();
state.close();

And if you had a ResultSet you would close that too the same way. You will put this code at the point when you are done using your database. So if you are done at the end of the Try-Catch block, add a Finally block and put the code there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM