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.
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.
getConnection() is static because it's a factory method for different JDBC driver Connection implementations.
The JDBC driver files are installed in C:\program files\microsoft SQL server <ver> JDBC Driver\lib.
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.
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