开发者

Alternative way to load DB driver in Java

Is there any other way to load DB driver than clas开发者_高级运维s.forName?


Modern Drivers don't need to be registered, because they have a META-INF/services/java.sql.Driver file that declares the existence of the driver, by containing the name of the Driver class.

Just use DriverManager.getConnection(...), and it discovers the driver itself.


EDIT @Thilo: I just tested it with PostgreSQL, and it works:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JdbcDriverLoadTest {

    public static void main(String[] args) throws SQLException {
        Connection c = DriverManager.getConnection("jdbc:postgresql://localhost:5434/IKOffice_Core", "ik", "ik0000");
        System.out.println(c.getMetaData().getDatabaseProductName());
    }

}


Modern JDBC drivers are supposed to provide enough metadata in their jar file manifest, so you may not need to do anything.

The main point of Class#forName is to remove the compile-time dependency on the particular JDBC driver (and make it configurable at run-time). If you are using Oracle driver code in your program anyway (to use their non-standard JDBC extensions) and have no compulsions to hardcode the driver class name, you can also just create a regular instance of the driver class.

 new oracle.jdbc.driver.OracleDriver();


Often, you can just create an instance of it, but that results in a hard dependency on a particular driver.

The reason what Class.forName is used is because you can make it configurable. The reason it works is because it triggers the class's static initializers to run, which allow it to register with jdbc.

In short, as far as I'm aware, you have two options:

  • Class.forName - allows configurable driver - nice
  • direct instantiation - creates solid class dependency - not nice


You can also add the driver class to the system property jdbc.drivers which is a list of colon-separated driver classnames that the DriverManager class loads.

Example:

java -Djdbc.drivers=oracle.jdbc.driver.OracleDriver MyApp

Source: The DriverManager javadocs.


com.mysql.jdbc.Driver dr = null;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜