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