Is there any other way to load DB driver than class.forName? This question is asked by my friend and looking for answer.
Any help would be very helpful.
Is there any other way to load DB driver than class.forName? This question is asked by my friend and looking for answer.
Any help would be very helpful.
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:
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();
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.openConnection(...), 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());
}
}
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.