Correctly Open and Close database connection


 

Correctly Open and Close database connection

In this tutorial you will learn how to open and close a database connection in JDBC

In this tutorial you will learn how to open and close a database connection in JDBC

Completely Open and Close A Database Connection

Database Connection handling is very important for any application. Most of the application performance depends on database connectivity. Therefore it is very important to open and close database connections properly. If any database connection is open then it takes the resources of the database such as memory, cursors, locks , temporary tables all are are engaged. To release the connection object it is very important to close the database connection after it is used. Database connection is closed by calling a close method of connection object.

An example of database proper connection opening and closing is given below

 

CompletlyOpenAndCloseConnection.java

package roseindia.net;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class CompletlyOpenAndCloseConnection {
	static Connection connection=null;
public CompletlyOpenAndCloseConnection(){
	try{
	Class.forName("com.mysql.jdbc.Driver");
	}catch(ClassNotFoundException e){
	System.out.println(e.toString());
	}
    }
	public Connection getConnection(String connectinUrl,String userName,String userPass) throws SQLException{
		Connection con=null;
		if(connection!=null){
			System.out.println("Catnt Create a connection........");
		}else{
			con=DriverManager.getConnection(connectinUrl,userName,userPass);
			System.out.println("A new connection created \n");
		}
		try{
			
		}catch(Exception e){
			System.out.println(e.toString());
		}
		return con;
	}
	public static void main(String []args) throws SQLException{
		String connectionUrl="jdbc:mysql://localhost:3306/student";
		String userName="root";
		String userPass="root";
		CompletlyOpenAndCloseConnection connectionExample=new CompletlyOpenAndCloseConnection();
		try{
			connection=connectionExample.getConnection(connectionUrl, userName, userPass);
		}catch(Exception e){
			System.out.println(e.toString());
		}finally{
			System.out.println("Closing a conection");
			connection.clearWarnings();
			System.out.println();
			connection.close();
			System.out.println("Connection closed.........");
		}
		
	}
}

When you run this application it will display message as shown below:


A new connection created

Closing a conection

Connection closed.........

Download this example code

Ads