ÔÚJdbcUtilsÖд´½¨Á¬½ÓÇ°ÎÒÃÇÐèÒª¼ÓÈëÕâ¾ä»°
Class.forName("com.mysql.jdbc.Driver");
´«Èë com.mysql.jdbc.Driver Ö®ºó,¾ÍÖªµÀÎÒÁ¬½ÓµÄÊý¾Ý¿âÊÇ mysql
¹Ù·½ÎĵµµÄÃèÊö£ºhttps://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#forName(java.lang.String)
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µÄ×÷ÓÃÊÇ»ùÓÚ·´Éä×¢²áÇý¶¯£¬
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())