2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-04-28 16:49:39 +02:00
In the past, it was required to load a JDBC driver before creating a ``++java.sql.Connection++``. Nowadays, when using JDBC 4.0 drivers, this is no longer required and ``++Class.forName()++`` can be safely removed because JDBC 4.0 (JDK 6) drivers available in the classpath are automatically loaded.
This rule raises an issue when ``++Class.forName()++`` is used with one of the following values:
* ``++com.mysql.jdbc.Driver++``
* ``++oracle.jdbc.driver.OracleDriver++``
* ``++com.ibm.db2.jdbc.app.DB2Driver++``
* ``++com.ibm.db2.jdbc.net.DB2Driver++``
* ``++com.sybase.jdbc.SybDriver++``
* ``++com.sybase.jdbc2.jdbc.SybDriver++``
* ``++com.teradata.jdbc.TeraDriver++``
* ``++com.microsoft.sqlserver.jdbc.SQLServerDriver++``
* ``++org.postgresql.Driver++``
* ``++sun.jdbc.odbc.JdbcOdbcDriver++``
* ``++org.hsqldb.jdbc.JDBCDriver++``
* ``++org.h2.Driver++``
* ``++org.firebirdsql.jdbc.FBDriver++``
* ``++net.sourceforge.jtds.jdbc.Driver++``
* ``++com.ibm.db2.jcc.DB2Driver++``
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Demo {
private static final String DRIVER_CLASS_NAME = "org.postgresql.Driver";
private final Connection connection;
public Demo(String serverURI) throws SQLException, ClassNotFoundException {
Class.forName(DRIVER_CLASS_NAME); // Noncompliant; no longer required to load the JDBC Driver using Class.forName()
connection = DriverManager.getConnection(serverURI);
}
}
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Demo {
private final Connection connection;
public Demo(String serverURI) throws SQLException {
connection = DriverManager.getConnection(serverURI);
}
}
----
2021-04-28 18:08:03 +02:00
2021-09-20 15:38:42 +02:00
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Remove this "Class.forName()", it is useless.
2021-09-20 15:38:42 +02:00
endif::env-github,rspecator-view[]