Tiiba
Tiiba

Reputation: 67

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.

Upvotes: 4

Views: 357

Answers (4)

Hot Licks
Hot Licks

Reputation: 47729

The reason is that if you use EmbeddedDriver.connect then the JVM will load the EmbeddedDriver class when the class containing the statement is initialized. Among other things, if EmbeddedDriver is not found in your class path this will cause the program to fail, even though the EmbeddedDriver class would never actually be used. (There are other reasons for wanting to delay resolving the class as well.)

Upvotes: 1

mxb
mxb

Reputation: 3330

I think that was required in the first versions of JDBC to ensure that DriverManager had the driver class loaded when requesting the connection. Direct access to the driver class in the code would have required the availability of the driver JAR at compile time and it was not the desired behavior from JDBC API.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201447

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.

Upvotes: 6

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

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.

Upvotes: 3

Related Questions