Following code:
Class.forName(dbDriver); // "org.postgres.Driver" or "com.mysql.jdbc.Driver"
is / was necessary to open JDBC connection.
I have heard that it is no longer needed with modern JDBC drivers. However I can't remove it in my project, because I'm getting No suitable driver found
exception. I am using postgresql-9.1-901.jdbc3.jar
, Java7 and tomcat7.
When can I omit Class.forName(...)
construct?
The java. lang. Class. forName(String name, boolean initialize, ClassLoader loader) method returns the Class object associated with the class or interface with the given string name, using the given class loader.
The Class. forName is used to load any given class (within double quotes as String) at run time. For example, when we use IDE, we see there will be a GUI builder which allows us to drag and drop the buttons, text fields, etc. This drag and drop mechanism internally requires certain classes to be loaded at run time.
Use the Class. forName() method to load the driver. The forName() method dynamically loads a Java class at runtime. When an application calls the forName() method, the Java Virtual Machine (JVM) attempts to find the compiled form (the bytecode) that implements the requested class.
The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class.
Class.forName() is not needed since JDBC 4.0.
Here is an excerpt from Java Tutorials on JDBC.
In previous versions of JDBC, to obtain a connection, you first had to initialize your JDBC driver by calling the method Class.forName. This methods required an object of type java.sql.Driver. Each JDBC driver contains one or more classes that implements the interface java.sql.Driver. The drivers for Java DB are org.apache.derby.jdbc.EmbeddedDriver and org.apache.derby.jdbc.ClientDriver, and the one for MySQL Connector/J is com.mysql.jdbc.Driver. See the documentation of your DBMS driver to obtain the name of the class that implements the interface java.sql.Driver.
Any JDBC 4.0 drivers that are found in your class path are automatically loaded. (However, you must manually load any drivers prior to JDBC 4.0 with the method Class.forName.)
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