Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is JDBC dynamically loaded instead of imported? [duplicate]

In JDBC, I only see examples using

Class.forName("com.mysql.jdbc.Driver", true, cl);

and haven't seen one using

import com.mysql.jdbc.Driver;

Is it because we want to let a driver package be dynamically provided at execution time, so can be known only at execution time?

If we have a fixed driver package known before execution, is it possible to go with the second way? How would you compare the two ways?

Thanks.

like image 724
Tim Avatar asked Jun 10 '18 15:06

Tim


People also ask

Why do we write class forName () in 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. This method is preferable because it allows you to make the driver registration configurable and portable.

Is getConnection a static method?

getConnection() is static because it's a factory method for different JDBC driver Connection implementations.

Where do I put my JDBC driver?

The JDBC driver files are installed in C:\program files\microsoft SQL server <ver> JDBC Driver\lib.


1 Answers

I only see examples using

Then you're reading really old stuff about JDBC. This is not useful anymore, for quite a long time. It was necessary to load the driver class to make sure the necessary driver was loaded, and able to handle connections to the provided database URLs, before trying to do so.

The JDBC abstractions are all you need to access a database, and you shouldn't care whether you're dealing with a MySQL driver or an Oracle driver, or whatever. Loading the driver dynamically, at runtime, allows removing the driver jar file from the compile classpath, and making sure you only rely on the standard JDBC classes and interfaces.

Note that importing a class doesn't do anything, other than allowing you to use the simple class name in your code. It's not equivalent to loading and initializing a class, which is what the first snippet does.

like image 123
JB Nizet Avatar answered Sep 30 '22 07:09

JB Nizet