Search code examples
javajdbcimportdynamic-loading

Why is JDBC dynamically loaded instead of imported?


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.


Solution

  • 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.