jdbcdell驱动管理器器使用什么来装载合适的jdbc驱动

posts - 340,&
comments - 67,&
trackbacks - 0
参见如下简单的程序
import java.sql.*;
public class DBTest {
private static final String USERNAME = "root";
private static final String PASSWD = "root";
private static final String DATABASE = "test";
private static final String DBMS = "mysql";
private static final String HOST = "localhost";
private static final String PORT = "3306";
private static final String DSN = "jdbc:" + DBMS + "://" + HOST + ":" + PORT + "/" + DATABASE;
public static void main(String[] args) {
Connection conn = DriverManager.getConnection(DSN, USERNAME, PASSWD);
String query = "SELECT * FROM user";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getInt(3));
} catch (SQLException e) {
e.printStackTrace();
下面我们来分析 DriverManager 的这个方法:
public static Connection getConnection(String url,
String user,
String password)
throws SQLException
查看一下DriverManager源码,代码块我按执行步骤全部贴出来:
1. 调用getConnection()方法
* Attempts to establish a connection to the given database URL.
* The &code&DriverManager&/code& attempts to select an appropriate driver from
* the set of registered JDBC drivers.
* @param url a database url of the form
* &code&jdbc:&em&subprotocol&/em&:&em&subname&/em&&/code&
* @param user the database user on whose behalf the connection is being
* @param password the user's password
* @return a connection to the URL
* @exception SQLException if a database access error occurs
public static Connection getConnection(String url,
String user, String password) throws SQLException {
java.util.Properties info = new java.util.Properties();
// Gets the classloader of the code that called this method, may
// be null.
ClassLoader callerCL = DriverManager.getCallerClassLoader();
if (user != null) {
info.put("user", user);
if (password != null) {
info.put("password", password);
return (getConnection(url, info, callerCL));
2. 调用实际起作用的getConnection()方法
Worker method called by the public getConnection() methods.
private static Connection getConnection(
String url, java.util.Properties info, ClassLoader callerCL) throws SQLException {
java.util.Vector drivers = null;
* When callerCl is null, we should check the application's
* (which is invoking this class indirectly)
* classloader, so that the JDBC driver class outside rt.jar
* can be loaded from here.
synchronized(DriverManager.class) {
// synchronize loading of the correct classloader.
if(callerCL == null) {
callerCL = Thread.currentThread().getContextClassLoader();
if(url == null) {
throw new SQLException("The url cannot be null", "08001");
println("DriverManager.getConnection(\"" + url + "\")");
if (!initialized) {
initialize();
synchronized (DriverManager.class){
// use the readcopy of drivers
drivers = readD
// Walk through the loaded drivers attempting to make a connection.
// Remember the first exception that gets raised so we can reraise it.
SQLException reason = null;
for (int i = 0; i & drivers.size(); i++) {
DriverInfo di = (DriverInfo)drivers.elementAt(i);
// If the caller does not have permission to load the driver then
// skip it.
if ( getCallerClass(callerCL, di.driverClassName ) != di.driverClass ) {
skipping: " + di);
trying " + di);
Connection result = di.driver.connect(url, info);
if (result != null) {
// Success!
println("getConnection returning " + di);
return (result);
} catch (SQLException ex) {
if (reason == null) {
// if we got here nobody could connect.
if (reason != null)
println("getConnection failed: " + reason);
println("getConnection: no suitable driver found for "+ url);
throw new SQLException("No suitable driver found for "+ url, "08001");
&这里有几个比较重要的地方,一个L25的initialize()方法,下面是他的源码
1 // Class initialization.
static void initialize() {
if (initialized) {
initialized = true;
loadInitialDrivers();
println("JDBC DriverManager initialized");
11 private static void loadInitialDrivers() {
drivers = (String) java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("jdbc.drivers"));
} catch (Exception ex) {
drivers = null;
// If the driver is packaged as a Service Provider,
// load it.
// Get all the drivers through the classloader
// exposed as a java.sql.Driver.class service.
DriverService ds = new DriverService();
// Have all the privileges to get all the
// implementation of java.sql.Driver
java.security.AccessController.doPrivileged(ds);
println("DriverManager.initialize: jdbc.drivers = " + drivers);
if (drivers == null) {
while (drivers.length() != 0) {
int x = drivers.indexOf(':');
if (x & 0) {
drivers = "";
driver = drivers.substring(0, x);
drivers = drivers.substring(x+1);
if (driver.length() == 0) {
println("DriverManager.Initialize: loading " + driver);
Class.forName(driver, true,
ClassLoader.getSystemClassLoader());
} catch (Exception ex) {
println("DriverManager.Initialize: load failed: " + ex);
这一段就是加载数据库驱动的地方,以我用的connector/j为例,看L27,这个DriverService是一个内部类,代码如下:
1 // DriverService is a package-private support class.
2 class DriverService implements java.security.PrivilegedAction {
Iterator ps = null;
public DriverService() {};
public Object run() {
// uncomment the followin line before mustang integration
// Service s = Service.lookup(java.sql.Driver.class);
// ps = s.iterator();
ps = Service.providers(java.sql.Driver.class);
/* Load these drivers, so that they can be instantiated.
* It may be the case that the driver class may not be there
* i.e. there may be a packaged driver with the service class
* as implementation of java.sql.Driver but the actual class
* may be missing. In that case a sun.misc.ServiceConfigurationError
* will be thrown at runtime by the VM trying to locate
* and load the service.
* Adding a try catch block to catch those runtime errors
* if driver not available in classpath but it's
* packaged as service and that service is there in classpath.
while (ps.hasNext()) {
ps.next();
} // end while
} catch(Throwable t) {
// Do nothing
return null;
} //end run
36 } //end DriverService
L11的 sun.misc.Service.providers()方法是关键所在,代码如下
* Locates and incrementally instantiates the available providers of a
* given service using the given class loader.
* &p& This method transforms the name of the given service class into a
* provider-configuration filename as described above and then uses the
* &tt&getResources&/tt& method of the given class loader to find all
* available files with that name.
These files are then read and parsed to
* produce a list of provider-class names.
The iterator that is returned
* uses the given class loader to lookup and then instantiate each element
* of the list.
* &p& Because it is possible for extensions to be installed into a running
* Java virtual machine, this method may return different results each time
* it is invoked. &p&
The service's abstract service class
The class loader to be used to load provider-configuration files
and instantiate provider classes, or &tt&null&/tt& if the system
class loader (or, failing that the bootstrap class loader) is to
* @return An &tt&Iterator&/tt& that yields provider objects for the given
service, in some arbitrary order.
The iterator will throw a
&tt&ServiceConfigurationError&/tt& if a provider-configuration
file violates the specified format or if a provider class cannot
be found and instantiated.
* @throws ServiceConfigurationError
If a provider-configuration file violates the specified format
or names a provider class that cannot be found and instantiated
* @see #providers(java.lang.Class)
* @see #installedProviders(java.lang.Class)
public static Iterator providers(Class service, ClassLoader loader)
throws ServiceConfigurationError
return new LazyIterator(service, loader);
* Private inner class implementing fully-lazy provider lookup
private static class LazyIterator implements Iterator {
Enumeration configs = null;
Iterator pending = null;
Set returned = new TreeSet();
String nextName = null;
private LazyIterator(Class service, ClassLoader loader) {
this.service =
this.loader =
public boolean hasNext() throws ServiceConfigurationError {
if (nextName != null) {
return true;
if (configs == null) {
String fullName = prefix + service.getName();
if (loader == null)
configs = ClassLoader.getSystemResources(fullName);
configs = loader.getResources(fullName);
} catch (IOException x) {
fail(service, ": " + x);
while ((pending == null) || !pending.hasNext()) {
if (!configs.hasMoreElements()) {
return false;
pending = parse(service, (URL)configs.nextElement(), returned);
nextName = (String)pending.next();
return true;
public Object next() throws ServiceConfigurationError {
if (!hasNext()) {
throw new NoSuchElementException();
String cn = nextN
nextName = null;
return Class.forName(cn, true, loader).newInstance();
} catch (ClassNotFoundException x) {
fail(service,
"Provider " + cn + " not found");
} catch (Exception x) {
fail(service,
"Provider " + cn + " could not be instantiated: " + x,
return null;
/* This cannot happen */
public void remove() {
throw new UnsupportedOperationException();
好了。经过各种进入,终于到达了目的地,上面这段代码就是加载数据库驱动的所在,请看LazyIterator里的从L57开始的这一段
实际上很简单,他就是去CLASSPATH里的library里找 &META-INF/services/java.sql.Driver 这个文件,其中 java.sql.Driver 这个名字是通过上面的 service.getName()获得的。 数据库驱动的类里都会有 META-INF 这个文件夹,我们可以MySQL的connector/j数据库驱动加到环境变量里后自己尝试一下输出,代码如下
3 import java.io.IOE
4 import java.net.URL;
5 import java.sql.D
6 import java.util.E
8 public class Test {
public static void main(String[] args) throws IOException {
Enumeration&URL& list = ClassLoader.getSystemResources("META-INF/services/" + Driver.class.getName());
while (list.hasMoreElements()) {
System.out.println(list.nextElement());
控制台会输出
jar:file:/usr/local/glassfish3/jdk7/jre/lib/resources.jar!/META-INF/services/java.sql.Driver
jar:file:/home/alexis/mysql-connector/mysql-connector-java-5.1.22-bin.jar!/META-INF/services/java.sql.Driver
看到了吗,这两个jar文件一个是jdk自带的,另一个是我们自己加到环境变量里的mysql驱动,然后我们再看看这两个java.sql.Driver里的东西,他们分别是
sun.jdbc.odbc.JdbcOdbcDriver
com.mysql.jdbc.Driver
自此,我们终于找到了我们需要加载的两个数据库驱动类的名称。然后再看LazyItarator里的next方法,注意到里面的forName了吧,这个方法就是加载类信息。顺便提一下,实际上forName方法里也是调用的ClassLoader的loadClass()方法来加载类信息的。
这里还有一步很关键的,就是加载类信息的时候发生了什么。我们看看 com.mysql.jdbc.Driver 的源码
1 public class Driver extends NonRegisteringDriver implements java.sql.Driver {
// ~ Static fields/initializers
// ---------------------------------------------
// Register ourselves with the DriverManager
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
// ~ Constructors
// -----------------------------------------------------------
* Construct a new driver and register it with DriverManager
* @throws SQLException
if a database error occurs.
public Driver() throws SQLException {
// Required for Class.forName().newInstance()
注意到这个static语句块了吧。就是这段代码,把自己注册到了DriverManager的driverlist里。
终于结束了,当所有驱动程序的Driver实例注册完毕,DriverManager就开始遍历这些注册好的驱动,对传入的数据库链接DSN调用这些驱动的connect方法,最后返回一个对应的数据库驱动类里的connect方法返回的java.sql.Connection实例,也就是我最开始那段测试代码里的conn。大家可以返回去看看DriverManager在initialize()结束后干了什么就明白
最后总结一下流程:
1. 调用 getConnection 方法
2. DriverManager 通过 &SystemProerty jdbc.driver 获取数据库驱动类名
通过ClassLoader.getSystemResources 去CLASSPATH里的类信息里查找 META-INF/services/java.sql.Driver 这个文件里查找获取数据库驱动名
3. 通过找的的driver名对他们进行类加载
4. Driver类在被加载的时候执行static语句块,将自己注册到DriverManager里去
5. 注册完毕后 DriverManager 调用这些驱动的connect方法,将合适的Connection 返回给客户端
阅读(...) 评论()JDBC环境设置
当前位置:
>> JDBC环境设置
JDBC环境设置
JDBC环境设置实例代码教程 - 要使用JDBC开发,设置JDBC环境的步骤如下所示。我们假设你在Windows平台上工作。
要使用JDBC开发,设置JDBC环境的步骤如下所示。我们假设你在Windows平台上工作。
安装J2SE开发工具包5.0(JDK 5.0).
请确保以下环境变量的设置,如下所述:
JAVA_HOME:&这个环境变量应该指向你安装JDK的目录下,如:C:\Program Files\Java\jdk1.5.0
CLASSPATH:&此环境变量应设置适当的路径,例如:C:\Program Files\Java\jdk1.5.0_20\jre\lib
PATH:&此环境变量应指向适当的JRE bin,例如: C:\Program Files\Java\jre1.5.0_20\bin.
这很可能你已设置了这些变量,但只是为了确保在这里是如何检查。
找到控制面板,然后双击“系统。如果您是Windows XP用户,必须打开“性能和维护”,然后会看到“系统”图标。
前往“高级”选项卡,然后单击“环境变量”。
现在,检查上面提到的所有变量都设置正确。
当安装J2SE开发工具包5.0(JDK 5.0)也同时自动获得JDBC包java.sql和javax.sql
安装数据库:
当然最重要的是一个实际正在运行的数据库表,可以查询和修改。
安装一个数据库,找一个最适合你的。你可以有很多选择,最常见的有:
MySQL:&MySQL是一个开放源码的数据库。您可以从下载。我们建议您下载完整的Windows安装。
此外,下载和安装以及。这些都是基于GUI的工具,使您的开发变得更加容易。
最后,在一个方便的目录中下载并解压缩(MySQL的JDBC驱动程序)。对于本教程中,我们将假定您已经安装了驱动程序在C:\Program Files\MySQL\mysql-connector-java-5.1.8.
因此设置CLASSPATH变量设置为C:\Program Files\MySQL\mysql-connector-java-5.1.8\mysql-connector-java-5.1.8-bin.jar。根据您的安装你的驱动程序版本可能会有所不同。
PostgreSQL:&PostgreSQL是一个开放源码的数据库。您可以从。
Postgres安装包含一个基于GUI的管理工具,叫pgAdmin III。还包括JDBC驱动程序的安装。
Oracle:&Oracle数据库是甲骨文公司出售的商业数据库。我们假设您有必要的配电介质来安装它。
Oracle安装包括一个基于GUI的管理工具,称为企业管理。还包括JDBC驱动程序的安装。
安装数据库驱动:
最新的JDK包含JDBC-ODBC桥驱动程序,使大多数开放式数据库连接(ODBC)驱动程序提供给程序员使用JDBC API。
现在大多数的数据库供应商提供适当的JDBC驱动程序以及数据库安装。所以,你不应该担心这部分内容。
设置数据库认证:
在本教程中,我们将使用MySQL数据库。当您安装任何上述数据库中,管理员ID设置为root,并规定设置您选择的密码。
使用root ID和密码,你可以创建另一个用户ID和密码,或者您可以使用您的JDBC应用程序的根ID和密码。
有各种不同的数据库操作,如数据库的创建和删除,这需要管理员ID和密码。
对于其余JDBC教程,我们将使用MySQL数据库的用户名ID和密码。
如果没有足够的权限来创建新的用户,那么可以问数据库管理员(DBA)创建一个用户ID和密码。
创建数据库:
要创建EMP数据库,请使用下列步骤:
打开命令提示符并更改到安装目录如下:
C:\&cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin&
注:&mysqld.exe路径可能会有所不同,具体取决于你的系统上的MySQL安装的位置。还可以检查文件上如何启动和停止数据库服务器。
通过执行下面的命令启动数据库服务器,如果它已经没有在运行。
C:\Program Files\MySQL\bin&mysqld
C:\Program Files\MySQL\bin&
通过执行下面的命令创建EMP数据库
C:\Program Files\MySQL\bin& mysqladmin create EMP -u root -p
Enter password: ********
C:\Program Files\MySQL\bin&
要创建EMP数据库中的Employees表,请使用下列步骤:
打开命令提示符并更改到安装目录如下:
C:\&cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin&
登陆到数据库如下:
C:\Program Files\MySQL\bin&mysql -u root -p
Enter password: ********
创建数据库表Employee&如下:
mysql& use EMP;
mysql& create table Employees
-& id int not null,
-& age int not null,
-& first varchar (255),
-& last varchar (255)
Query OK, 0 rows affected (0.08 sec)
创建数据记录
最后,创建几个EMPLOYEE表中的记录如下:
mysql& INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
Query OK, 1 row affected (0.05 sec)
mysql& INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');
Query OK, 1 row affected (0.00 sec)
mysql& INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');
Query OK, 1 row affected (0.00 sec)
mysql& INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');
Query OK, 1 row affected (0.00 sec)
为了完整地理解MySQL数据库,学习
现在,可以开始尝试使用JDBC。下一个教程将介绍JDBC编程的例子。驱动程序管理器
odbc driver manager odbc
&2,447,543篇论文数据,部分数据来源于
如果使用一个驱动程序管理器,那么可以用一个 ODBC 级数据源名称替代 SAMPLE。
If you're using a driver manager, SAMPLE can be replaced by an ODBC-level data source name.
它经过重新编写,能支持遵从 ODBC V3 的驱动程序和驱动程序管理器。
It was written from the ground-up to support ODBC V3 compliant drivers and driver managers.
可以通过两种方式创建连接:通过直接链接或使用驱动程序管理器。
The connection can be created in two ways: by direct linking or by using the driver manager.
$firstVoiceSent
- 来自原声例句
请问您想要如何调整此模块?
感谢您的反馈,我们会尽快进行适当修改!
请问您想要如何调整此模块?
感谢您的反馈,我们会尽快进行适当修改!

我要回帖

更多关于 amd驱动管理器 的文章

 

随机推荐