µ±Ç°Î»Ö㺠´úÂëÃÔ >> ×ÛºÏ >> ΪʲôҪдclass.forname£¬¶øClassLoaderÓÖÊÇ×öʲôµÄ
  Ïêϸ½â¾ö·½°¸

ΪʲôҪдclass.forname£¬¶øClassLoaderÓÖÊÇ×öʲôµÄ

Èȶȣº41   ·¢²¼Ê±¼ä£º2023-10-21 07:34:05.0

ÔÚJdbcUtilsÖд´½¨Á¬½ÓÇ°ÎÒÃÇÐèÒª¼ÓÈëÕâ¾ä»°

Class.forName("com.mysql.jdbc.Driver");

´«Èë com.mysql.jdbc.Driver Ö®ºó,¾ÍÖªµÀÎÒÁ¬½ÓµÄÊý¾Ý¿âÊÇ mysql

ΪʲôҪдclass.forname£¬¶øClassLoaderÓÖÊÇ×öʲôµÄ

¹Ù·½ÎĵµµÄÃèÊö£ºhttps://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#forName(java.lang.String)

ΪʲôҪдclass.forname£¬¶øClassLoaderÓÖÊÇ×öʲôµÄ

import com.mysql.jdbc.Driver;
import java.sql.*;public class JdbcDemo {public static void main(String[] args) throws SQLException, ClassNotFoundException {String url = "jdbc:mysql://127.0.0.1:3306/mydb";String username = "root";String password = "redhat";Class.forName("com.mysql.jdbc.Driver");Connection connection = DriverManager.getConnection(url, username, password);String sql = "SELECT * FROM msg";PreparedStatement prepareStatement = connection.prepareStatement(sql);ResultSet resultSet = prepareStatement.executeQuery();resultSet.next();String address = resultSet.getString("address");System.out.println(address);}
}

 com.mysql.jdbc.DriverµÄÄÚÈÝ

package com.mysql.jdbc;
public class Driver extends NonRegisteringDriver implements java.sql.Driver {public Driver() throws SQLException {}static {try {DriverManager.registerDriver(new Driver());} catch (SQLException var1) {throw new RuntimeException("Can't register driver!");}}
}

Ò²¾ÍÊÇ˵ÎÒÃÇ Class.forName ºÍÖ±½Óд DriverManager.registerDriver(new Driver) Á½Õß¹¦ÄÜÊǵÈͬµÄ¡£

ÔÙ¿´¿´DriverManagerÊÇÔõô˵µÄ

ΪʲôҪдclass.forname£¬¶øClassLoaderÓÖÊÇ×öʲôµÄ

 ËùÒÔËùÎÒÃǵÄClass.forNameµÄ×÷ÓÃÊÇ»ùÓÚ·´Éä×¢²áÇý¶¯£¬

CLass.forName£¨£©»¹ÓÐÁíÍâÒ»¸ö·½·¨

forName(String name, boolean initialize, ClassLoader loader)

      • ²ÎÊý

        ËùÐèµÄÀàµÄÍêÈ«ÏÞ¶¨Ãû name -

        initialize -Èç¹û trueÀཫ±»³õʼ»¯¡£¿´µ½javaÓïÑԹ淶12.4½Ú¡£

        loader -Àà×°ÔØÆ÷µÄÀà±ØÐë×°

        ½á¹û

        ±íʾËùÐèÀàµÄÀà¶ÔÏó

 Èç¹ûname±íʾÊý×éÀ࣬Ôò¼ÓÔØÊý×éÀàµÄ×é¼þÀàÐÍ£¬µ«²»³õʼ»¯¡£  

Class.forName("Foo")
is equivalent to:
Class.forName("Foo", true, this.getClass().getClassLoader())

 

  Ïà¹Ø½â¾ö·½°¸