Why Class.forName ("database driver")?

Why

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

instead

dbConnection = EmbeddedDriver.connect(strUrl, props);

?

Isn't it more error prone to specify a string rather than a class name that can be checked by the compiler? I saw an example when the class name was obtained from the configuration, but this is apparently a template that is used regardless of the alternatives available.

+4
source share
4 answers

With the JDBC 4.0 driver (and above) all you need is

dbConnection = DriverManager.getConnection(strUrl, props);

for DriverManagerjavadoc,

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

my.sql.Driver

JDBC, Class.forName(). , JDBC Class.forName(), .

+6

EmbeddedDriver. , "org.apache.derby.jdbc.EmbeddedDriver" .

"" EmbeddedDriver , .

, , ?

. Java , .

+3

, EmbeddedDriver.connect, JVM EmbeddedDriver, , , . , EmbeddedDriver , , EmbeddedDriver . ( , .)

+1

I think the first versions of JDBC needed to make sure that DriverManager loaded the driver class when requesting a connection. Direct access to the driver class in code would require a JAR driver at compile time, and this was not the desired behavior of the JDBC API.

0
source

Source: https://habr.com/ru/post/1547772/


All Articles