Raj
Raj

Reputation: 4010

Alternative way to load DB driver in Java

Is there any other way to load DB driver than class.forName?

Upvotes: 1

Views: 3886

Answers (5)

Bipin Yadav
Bipin Yadav

Reputation: 1

com.mysql.jdbc.Driver dr = null;

Upvotes: 0

Daniel
Daniel

Reputation: 28074

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());
    }

}

Upvotes: 9

dogbane
dogbane

Reputation: 274552

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.

Upvotes: 1

Thilo
Thilo

Reputation: 262494

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();

Upvotes: 4

developmentalinsanity
developmentalinsanity

Reputation: 6229

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

Upvotes: 1

Related Questions