DriverManager是怎么獲取到連接的?
1 Class.forName("oracle.jdbc.driver.OracleDriver");
2 DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orci8","userName","password");
每個 JDBC 驅(qū)動必須實現(xiàn) java.sql.Driver 接口,而 Class.forName 會在類加載器中加載,此時并不會產(chǎn)生 Driver 的對象,這種加載只會執(zhí)行這個類中的靜態(tài)塊。
而 JDBC 規(guī)范要求所有實現(xiàn)java.sql.Driver 接口的類,必須在靜態(tài)塊中調(diào)用 DriverManager.registerDriver 方法把自己注冊到 DriverManager 中去。DriverManager 通過搜尋已注冊的 Driver 實現(xiàn)類,調(diào)用 connect 方法從而獲得連接。
當(dāng)然了 connect 方法是在 Driver 接口中聲明的,由具體的 JDBC Driver 類去實現(xiàn)。這就是采用 Class.forName 方式獲得連接的辦法。
如mysql的Driver類
1 package com.mysql.jdbc;
2
3 import java.sql.SQLException;
4
5 /**
6 * The Java SQL framework allows for multiple database drivers. Each driver
7 * should supply a class that implements the Driver interface
8 *
9 * <p>
10 * The DriverManager will try to load as many drivers as it can find and then
11 * for any given connection request, it will ask each driver in turn to try to
12 * connect to the target URL.
13 *
14 * <p>
15 * It is strongly recommended that each Driver class should be small and
16 * standalone so that the Driver class can be loaded and queried without
17 * bringing in vast quantities of supporting code.
18 *
19 * <p>
20 * When a Driver class is loaded, it should create an instance of itself and
21 * register it with the DriverManager. This means that a user can load and
22 * register a driver by doing Class.forName("foo.bah.Driver")
23 *
24 * @see org.gjt.mm.mysql.Connection
25 * @see java.sql.Driver
26 * @author Mark Matthews
27 * @version $Id$
28 */
29 public class Driver extends NonRegisteringDriver implements java.sql.Driver {
30 // ~ Static fields/initializers
31 // ---------------------------------------------
32
33 //
34 // Register ourselves with the DriverManager
35 //
36 static {
37 try {
38 java.sql.DriverManager.registerDriver(new Driver());
39 } catch (SQLException E) {
40 throw new RuntimeException("Can't register driver!");
41 }
42 }
43
44 // ~ Constructors
45 // -----------------------------------------------------------
46
47 /**
48 * Construct a new driver and register it with DriverManager
49 *
50 * @throws SQLException
51 * if a database error occurs.
52 */
53 public Driver() throws SQLException {
54 // Required for Class.forName().newInstance()
55 }
56 }
posted on 2011-03-06 21:46
showsun 閱讀(434)
評論(0) 編輯 收藏 所屬分類:
J2SE