Saturday, 9 August 2014

JDBC : Load JDBC Driver

🚀 Master Java database programming and JDBC fundamentals!

🔔 Subscribe to Ram N Java on YouTube

Step 1: Download & Configure the MySQL JDBC Driver

Before your Java application can talk to a MySQL database, it requires the vendor-specific JDBC driver library (MySQL Connector/J):

  • Visit the official MySQL downloads site and choose MySQL Connector/J.
  • Select the Platform Independent option to download the ZIP distribution.
  • Extract the archive to locate the driver JAR file (e.g., mysql-connector-java.jar).
  • Add this JAR file to your project's lib folder and ensure it is included in your Java classpath.

Java Program: Loading Driver and Connecting

Here is the complete Java code showing how to dynamically load the driver class and open a database connection using DriverManager:

package com.ram.jdbc;

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

public class LoadJDBCDriverDemo {

    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/world";
    static final String USER = "root";
    static final String PASS = "root";

    public static void main(String[] args) {
        LoadJDBCDriverDemo demo = new LoadJDBCDriverDemo();
        demo.loadDriverAndConnect();
    }

    public void loadDriverAndConnect() {
        Connection conn = null;
        try {
            // Step 1: Load and register MySQL driver
            Class.forName(JDBC_DRIVER);
            System.out.println("Driver loaded successfully!");

            // Step 2: Establish connection via DriverManager
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            System.out.println("Connection established successfully: " + conn);

        } catch (ClassNotFoundException e) {
            System.err.println("JDBC Driver not found in classpath!");
            e.printStackTrace();
        } catch (SQLException e) {
            System.err.println("Failed to connect to database!");
            e.printStackTrace();
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                    System.out.println("Connection closed.");
                }
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
    }
}

Behind the Scenes: How Class.forName() Registers the Driver

How does calling Class.forName("com.mysql.jdbc.Driver") make DriverManager aware of the driver?

When you decompile com.mysql.jdbc.Driver from the JAR, you will see a static initialization block defined inside the class:

static {
    try {
        java.sql.DriverManager.registerDriver(new Driver());
    } catch (SQLException E) {
        throw new RuntimeException("Can't register driver!");
    }
}

When Class.forName() loads the class into memory, the JVM executes this static block immediately, automatically creating an instance of the driver and registering it with DriverManager.

Related Tutorials You Might Enjoy


Click here to watch in Youtube : https://www.youtube.com/watch?v=fA539fwWtHY

Click the below Image to Enlarge
JDBC : Load JDBC Driver
JDBC : Load JDBC Driver
JDBC : Load JDBC Driver
JDBC : Load JDBC Driver
JDBC : Load JDBC Driver
JDBC : Load JDBC Driver
LoadJDBCDriver.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class LoadJDBCDriver
{
    private Connection connection = null;

    public static void main( String[] args )
    {
        try
        {
            LoadJDBCDriver loadJDBCDriver = new LoadJDBCDriver();
            loadJDBCDriver.loadDriver();
        }
        catch( ClassNotFoundException | SQLException e )
        {
            e.printStackTrace();
        }

    }

    private void loadDriver() throws ClassNotFoundException, SQLException
    {
        /*
         * This will load the MySQL driver and Register the Driver in DriverManager, each DB has its own driver
         */

        Class.forName("com.mysql.jdbc.Driver");

        /*
         * Setup the connection with the DB.
         */

        connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/world", "root", "root");

        System.out.println("Connection Object :  " + connection);
    }

}

Output
Connection Object :  com.mysql.jdbc.JDBC4Connection@1aa159bb

Environment Used 

JDK version : 1.7.0_51
Mysql Server version : 5.6.19 

To Download LoadJDBCDriverDemoApp Project Click the below link

https://sites.google.com/site/javaee4321/jdbc/LoadJDBCDriverDemoApp.zip?attredirects=0&d=1

See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • No comments:

    Post a Comment

    Tutorials