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) {
      finally {
         try {
         catch (SQLException sqlException) {

This will produce the following output −

connection is open

Here is the screenshot of the output −