JDBC Class.forName() is no longer required

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();
        }

    }


}

References

author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar
3000
newest oldest most voted
xyz
Guest
xyz

good