JDBC Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 2.11

Closing the Database Connection - con.close()

This section describes how to close database connections.

When you obtained a connection object with DriverManager.getConnection() successfully, you can create statement objects and execute them with this connection object. But when you are done with this connection, you should close it to free resources associated this connection on the SQL server. To close a connection, you should call the close() method on this connection object.

The tutorial program below shows you how to call close() on a connection object. isClosed() method is called to verify the status of the connection object.

/**
 * CloseConnection.java
 * Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
 */
import java.sql.*;
public class CloseConnection {
  public static void main(String [] args) {
    Connection con = null;
    try {

// Load Microsoft JDBC Driver 1.0
      Class.forName(
        "com.microsoft.sqlserver.jdbc.SQLServerDriver");

// Obtaining a connection to SQL Server
      con = DriverManager.getConnection(
          "jdbc:sqlserver://localhost:1269;"
        + "user=sa;password=HerongYang");

// Connection is ready to use
      DatabaseMetaData meta = con.getMetaData();
      System.out.println("Server name: " 
        + meta.getDatabaseProductName());
      System.out.println("Server version: "
        + meta.getDatabaseProductVersion());

// Closing the connection
      con.close();
      if (con.isClosed()) 
        System.out.println("Connection closed.");

    } catch (java.lang.ClassNotFoundException e) {
      System.err.println("ClassNotFoundException: "
        +e.getMessage());
    } catch (SQLException e) {
      System.err.println("SQLException: "
        +e.getMessage());
    }
  }
}

If you run this program, you will get:

C:\>\progra~1\java\jdk1.6.0_02\bin\java -cp .;\local\lib\sqljdbc.jar
   CloseConnection

Server name: Microsoft SQL Server
Server version: 9.00.1399
Connection closed.

Sections in This Chapter

Installing Microsoft JDBC Driver for SQL Server

Loading Driver Class with Class.forName()

DriverManager.getConnection() and Connection URL

Specifying Port Number in Connection URL

Closing the Database Connection - con.close()

Specifying Database Name in Connection URL

Incorrect Database Name in Connection URL

Creating Connections with DataSource Class

Dr. Herong Yang, updated in 2007
Closing the Database Connection - con.close()