There are two ways to load a driver:
Class.forName()
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..
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With