DriverManager是怎么获取到连接的?
1 Class.forName("oracle.jdbc.driver.OracleDriver");
2 DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orci8","userName","password");
每个 JDBC 驱动必须实现 java.sql.Driver 接口,而 Class.forName 会在类加载器中加载,此时并不会产生 Driver 的对象,这种加载只会执行这个类中的静态块。
而 JDBC 规范要求所有实现java.sql.Driver 接口的类,必须在静态块中调用 DriverManager.registerDriver 方法把自己注册到 DriverManager 中去。DriverManager 通过搜寻已注册的 Driver 实现类,调用 connect 方法从而获得连接。
当然了 connect 方法是在 Driver 接口中声明的,由具体的 JDBC Driver 类去实现。这就是采用 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 阅读(425)
评论(0) 编辑 收藏 所属分类:
J2SE