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 −

Updated on: 12-Dec-2019

951 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements