Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Class.forName() mechanism needed? [duplicate]

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?

like image 296
FazoM Avatar asked Oct 28 '15 12:10

FazoM


People also ask

How does class forName () work in Java?

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.

What is the need of class forName?

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.

What is the role of class forName () in JDBC?

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.

What does JDBC forName () method does for you when you connect to any DB?

The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class.


1 Answers

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.)

like image 134
Developer Marius Žilėnas Avatar answered Oct 07 '22 12:10

Developer Marius Žilėnas