JDBC connection

In this Tutorial we want to describe you a code that helps you in understanding a Jdbc Connection.

JDBC connection

     

The JDBC connection implements a connection with database in front end application. The JDBC includes execution of SQL queries return a result set over that specified connection.

 Understand with Example

In last Tutorial we illustrates you JDBC url connection. The current Tutorial helps you to understand JDBC connection. The code explains you   how creating and closing of connection is done.

For this program code we have a class Jdbc Connection, We have a list of method required to connect and close the connection. Before the implementation of class we need to import a package java.sql.* needed for network interface between url and back end.

   Loading a driver is done by calling a class.forName ( ) and accept the driver class as argument.

   DriverManager.getConnection  ( ) :This method returns you an connection object.DriverManager.getConnection built a connection with database.

Using this method we establish a connection between url and database. Once the connection is built,println print the connection is created

   con.close ( ) : An object of connection is used to close the connection between database and url.

Finally the println print the connection is closed.In case there is an exception in try block, during the establishment of connection between the front end in java application(url) and backend. The catch block is responsible for handling the exception.

JdbcConnection.java

 
import java.sql.*;
public class JdbcConnection {
    public static void main(String args[]) {
        Connection con = null;
        String url = "jdbc:mysql://localhost:3306/";
        String db = "komal";
        String driver = "com.mysql.jdbc.Driver";
        String user = "root";
        String pass = "root";
        try {
            Class.forName(driver);
            con = DriverManager.getConnection(url + db, user, pass);
            System.out.println("jdbc driver for mysql : " + driver);
            System.out.println("Connection url : " + url + db);
            System.out.println("Connection is created...");
            con.close();
            System.out.println("Connection is closed...");
        } catch (Exception e) {
            System.out.println(e);
        }
    }
} 

Output

Connection is created...
Connection is closed...

Download code

Ads