Class.Forname () loading data driver

xiaoxiao2021-03-06  20

When you start contacting JDBC, there is a doubt that you can load the mysql driver if you perform class.forname ("com.mysql.jdbc.driver). What is the initialization process of JDBC driver? When connecting to a specific database, how does the JDBC DRIVERMANAGER work? With such a few doubts, I downloaded the driver code of MySQL, combined with the J2SDK source code, analyzed the JDBC driver management mechanism. 1. Analyze the implementation code of the JDBC driver management section: At the JDBC level, Sun mainly defines one interface driver and two classes: DirverManager and Driverinfo. Each JDBC driver must implement a DRIVER interface (this is called com.mysql.jdbc.driver in MySQL Connector / J Drive). DriverManager is responsible for managing all Driver objects, including the registration driver; selecting the appropriate Driver to create a connection to a database; and perform some DRIVER information management, etc.. Driverinfo is very simple, used to save DRIVER information, only 3 member variables, driver, driverclass, and driverclassname, significant is very obvious. Let's take a look at the key code in DriverManager.java: private static java.util.Vector drivers = new java.util.Vector (); all Driver objects are saved in a vector array. Driver registration function is called registerDriver, will need to register Driver objects can be passed: public static synchronized void registerDriver (java.sql.Driver driver) throws SQLException {if {// If not initialized, initialize initialize (initialized!) (); DRIVERINFO DI = New DriverInfo (); // The actual saved is not Driver, but a DriverInfo object, but DriverInfo's other members can be derived from Driver, so personal feel that DriverInfo object can be available, directly useful Driver should be. Di.driver = driver; di.driverclass = driver.driverclass (); di.driverclassname = di.driverclass.getName (); drivers.addelement (di); // Add DriverInfo object to array println ("RegisterDriver:" DI);} This completes the registration process of the driver.

Then look at the key code to establish a database connection, the function getConnection omitted some non-critical code: private static synchronized Connection getConnection (String url, java.util.Properties info, ClassLoader callerCL) throws SQLException {SQLException reason = null; / / Polly all DriverInfo objects. For (int i = 0; i

Driver class discovery implementation is very simple, public class Driver extends NonRegisteringDriver implements java.sql.Driver {static {try {java.sql.DriverManager.registerDriver (new Driver ());} catch (SQLException E) {throw new RuntimeException ( " Can't register driver! ");}}

转载请注明原文地址:https://www.9cbs.com/read-40397.html

New Post(0)