Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Class.forName('database driver')?

Why

Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
dbConnection = DriverManager.getConnection(strUrl, props);

instead of

dbConnection = EmbeddedDriver.connect(strUrl, props);

?

Isn't it more error-prone to specify a string, instead of a class name that can be checked by the compiler? I saw an example where the class name was obtained from configuration, but this seems to be the pattern that is used regardless of available alternatives.

like image 501
Tiiba Avatar asked Dec 25 '22 06:12

Tiiba


2 Answers

With a JDBC 4.0 driver (and up), all you need is

dbConnection = DriverManager.getConnection(strUrl, props);

per the DriverManager javadoc,

JDBC 4.0 Drivers must include the file META-INF/services/java.sql.Driver. This file contains the name of the JDBC drivers implementation of java.sql.Driver. For example, to load the my.sql.Driver class, the META-INF/services/java.sql.Driver file would contain the entry:

my.sql.Driver

Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.

like image 156
Elliott Frisch Avatar answered Dec 28 '22 07:12

Elliott Frisch


The first code snippet lets your program avoid a compile-time dependency on the EmbeddedDriver class. For example, you could put the "org.apache.derby.jdbc.EmbeddedDriver" string in your configuration file, and read it at run-time.

The second code snippet "bakes in" the dependency on the EmbeddedDriver class into the body of your program, making it impossible to switch the driver without recompiling your code.

Isn't it more error-prone to specify a string, instead of a class name that can be checked by the compiler?

That is absolutely true. Specifying a Java string literal for the name of the driver class is not a proper way to go, because your program would not gain any flexibility from accessing the class by name.

like image 31
Sergey Kalinichenko Avatar answered Dec 28 '22 06:12

Sergey Kalinichenko