A Developer's Diary

Oct 2, 2013

Automatically registering the jdbc driver

A jdbc driver can be registered with the Driver Manager in four ways.
1. Automatic Registration
2. Using Class.forName("DRIVER_NAME")
3. Using property -Djdbc.drivers=DRIVER_NAME
4. Explicit registration using the new operator

Automatic Registration
Starting JDBC 4.0, the DriverManager methods getConnection() and getDrivers() have been enhanced to support automatic registration of the driver using the Service Provider mechanism.

JDBC 4.0 Drivers must include the file java.sql.Driver under META-INF/services/ directory. This file contains the name of the jdbc driver implementation. For example mysql-connector-java-5.1.18.jar has entry com.mysql.jdbc.Driver in the java.sql.Driver file under the directory META-INF/services


In the code below we are calling DriverManager.getConnection() without invoking any code for loading or registering the driver

package dev.faqs.jdbc.test;

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

public class JdbcDriverTest
{
    private static final String ORACLE_JDBC_URL = "jdbc:oracle:thin:@localhost:1521:medb";

    private static final String QUERY_EMPLOYEE = "SELECT E.FIRST_NAME, E.LAST_NAME, E.EMAIL, E.CITY FROM EMPLOYEE E WHERE E.EMP_ID = ?";

    public static void main(String[] args)
    {
        try
        {
            Connection connection = DriverManager.getConnection(ORACLE_JDBC_URL, "dev", "dev");
            PreparedStatement ps = connection.prepareStatement(QUERY_EMPLOYEE);
            ps.setLong(1, 1);

            ResultSet rs = ps.executeQuery();
            while (rs.next())
            {
                System.out.println("Name: " + rs.getString("FIRST_NAME") + " " + rs.getString("LAST_NAME"));
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }
}

No comments :

Post a Comment