JDBC Class.forName() is no longer required
By:Roy.LiuLast updated:2019-08-11
Since Java 1.6, JDBC 4.0 API, it provides a new feature to discover java.sql.Driver automatically, it means the Class.forName is no longer required. Just put any JDBC 4.x driver in the project classpath, and Java is able to detect it.
For example, JDBC driver for PostgreSQL:
pom.xml
<dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>42.2.5</version> </dependency>
And it works:
package com.mkyong.jdbc; import java.sql.*; public class JDBCExample { public static void main(String[] args) { try { // this is optional @since 1.6 // Class.forName("org.postgresql.Driver"); // auto close connection try (Connection conn = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/test", "postgres", "password")) { Statement statement = conn.createStatement(); //... } catch (Exception e) { System.err.println("Something went wrong!"); e.printStackTrace();
From:一号门
COMMENTS