Is JDBC still using Class.forName?

When many friends manage their connections, they are still used to using the following methods to obtain connections.

@Test
public void testGetConnection() throws SQLException {
    
    
//        Class.forName("com.mysql.jdbc.Driver");//新版本不需要了
    Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF8", "username", "password");
    Statement statement = connection.createStatement();
    ResultSet resultSet = statement.executeQuery("select id from test");
    while (resultSet.next()){
    
    
        System.out.println(resultSet.getInt("id"));
    }
}

In fact, it is no longer needed in the new version of the JDK, Class.forName("com.mysql.jdbc.Driver"); this kind of very inelegant code.

Note: The new version of the JDK mentioned here does not refer to the high version, but the newly released JDK version. I checked the source code of the new version 1.6 and 1.7 and found that they have been processed.

The following method is the method in ServiceLoader, JDBC Driver loads through it.

If you don’t understand this, you can refer to: Java SPI

Get Driver
We can see that the class found through ServiceLoader has been loaded, but the initialization has not been performed.

So, in our code, we don't need:

Class.forName(“com.mysql.jdbc.Driver”);

Guess you like

Origin blog.csdn.net/trayvontang/article/details/108246032