
- Learn MySQL
- MySQL - Home
- MySQL - Introduction
- MySQL - Installation
- MySQL - Administration
- MySQL - PHP Syntax
- MySQL - Connection
- MySQL - Create Database
- MySQL - Drop Database
- MySQL - Select Database
- MySQL - Data Types
- MySQL - Create Tables
- MySQL - Drop Tables
- MySQL - Insert Query
- MySQL - Select Query
- MySQL - Where Clause
- MySQL - Update Query
- MySQL - Delete Query
- MySQL - Like Clause
- MySQL - Sorting Results
- MySQL - Using Join
- MySQL - NULL Values
- MySQL - Regexps
- MySQL - Transactions
- MySQL - Alter Command
- MySQL - Indexes
- MySQL - Temporary Tables
- MySQL - Clone Tables
- MySQL - Database Info
- MySQL - Using Sequences
- MySQL - Handling Duplicates
- MySQL - SQL Injection
- MySQL - Database Export
- MySQL - Database Import
Where we should close a connection in JDBC and MySQL?
You need to close connection in finally block. Following is the Java code to close connection in JDBC and MySQL −
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class CloseConnectionDemoInFinallyBlock { public static void main(String[] args) { String JDBCURL = "jdbc:mysql://localhost:3306/web?useSSL=false"; Connection con = null; try { con = DriverManager.getConnection(JDBCURL, "root", "123456"); System.out.println("connection is open"); } catch (Exception e) { e.printStackTrace(); } finally { try { con.close(); } catch (SQLException sqlException) { sqlException.printStackTrace(); } } } }
This will produce the following output −
connection is open
Here is the screenshot of the output −
- Related Articles
- What is the MySQL JDBC driver connection string?
- How to establish connection with JDBC?
- How to display the storage engine while implementing JDBC - MySQL CONNECTION query?
- What are native methods in Java and where should we use them?
- Can we use WHERE, AND & OR in a single MySQL query?
- Is it mandatory to close JDBC connections?
- Setting up a JDBC connection to remote SAP HANA system
- How to reconnect to websocket after close connection with HTML?
- How to determine database type (name) for a given JDBC connection?
- Why we mention in MySQL WHERE 1=0?
- Why should we use MySQL CASE Statement?
- How do we insert/store a file into MySQL database using JDBC?
- How to close the ResultSet cursor automatically, after commit in JDBC?
- During winters why do we see more fog in close areas where there are lots of trees?
- How to establish a connection with the database using the properties file in JDBC?

Advertisements