Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which approach is better to load a JDBC driver?

Tags:

java

jdbc

There are two ways to load a driver:

  1. Class.forName()

  2. DriverManager.registerDriver()

Method 1 internally also calls DriverManager.registerDriver and method 1 is the preferred way.

But why? Is there any small difference or is performance etc. better?
Any views are appreciated..

like image 421
harshit Avatar asked Apr 01 '09 17:04

harshit


People also ask

Which method is used for loading the driver in Java JDBC?

forName() The most common approach to register a driver is to use Java's Class. forName() method, to dynamically load the driver's class file into memory, which automatically registers it.

Which type of JDBC driver is faster Why?

JDBC Net pure Java driver(Type 4) is the fastest driver because it converts the JDBC calls into vendor specific protocol calls and it directly interacts with the database.

Which type of JDBC driver is used?

Type 1 JDBC drivers are used for testing JDBC applications against an ODBC data source. Type 2 JDBC drivers require a native database API to be used. Both Type 1 and Type 2 JDBC driver types mix a Java-based API with another API.


2 Answers

If you use Class.forName(), then you are not required to have any compile-time dependencies on a particular JDBC driver. This is particularly useful when you are writing code that can work with a variety of databases.

Consider the following code:

// Register the PostgreSQL driver
Class.forName("org.postgresql.Driver");

Now compare it to:

import org.postgresql.Driver;

// Register the PostgreSQL driver
DriverManager.registerDriver(new Driver());

And consider that in the first example, the class name could also have come from a properties file, XML file, etc., depending on what's convenient for your application.

like image 153
Matt Solnit Avatar answered Oct 18 '22 10:10

Matt Solnit


The JDBC API Tutorial and Reference is the best reference for such questions, a section of which addresses the role played by the Driver and DriverManager classes.

All Driver classes are expected to have a static initializer that is responsible for creating an instance of that Driver, and register it with the DriverManager, when the Driver class is loaded.

Additionally, the DriverManager.getConnection() is probably the only user-space friendly method in the class. Most of the other methods are usually not used by most developers using the JDBC API. So the old adage still stands - use Class.forName() to load the driver, and then use DriverManager.getConnection() to get a connection to the database.

like image 34
Vineet Reynolds Avatar answered Oct 18 '22 08:10

Vineet Reynolds