当前位置:首页 > 网络编程 > 软件语言 > DELPHI > JDBC到底是怎么连上数据库的?

JDBC到底是怎么连上数据库的?

点击次数:66 次 发布日期:2008-11-09 08:43:59 作者:源代码网
源代码网推荐
广告载入中
java.sql包中的 java.sql.Driver, jdbc.sql.Connection等提供给程序开发人员统一的开发接口


数据库提供商提供相应的实现,对程序开发人员来讲只要知道这些接口都有哪些方法就可以了


但我们可以深入一些 看看到底这里面都做了那些事, 同时也可以学习其中的编程模式(如Interface模式等)

软件开发网 www.mscto.com



1 Class.forName(String classname) 的源码为:


public final


class Class implements java.io.Serializable {


...


public static Class forName(String className)

软件开发网 www.mscto.com


throws ClassNotFoundException {


return forName0(className, true, ClassLoader.getCallerClassLoader());


}


...


}


关于forName0 请自己查看jdk source.


目的是把指定的Class装载到JVM中来。(注意class的装载、初始化过程)


在装载过程中将执行被装载类的static块(如下)


2 sun的JdbcOdbcDriver 源码:


public class JdbcOdbcDriver extends JdbcOdbcObject


implements JdbcOdbcDriverInterface


{


...


/**


* connect to DB


*/ 软件开发网 www.mscto.com


public synchronized Connection connect(String s, Properties properties)


throws SQLException


{ 软件开发网 www.mscto.com


if(JdbcOdbcObject.isTracing())


JdbcOdbcObject.trace("*Driver.connect (" s ")");

软件开发网 www.mscto.com


if(!acceptsURL(s))


return null;


if(hDbc != 0)

软件开发网 www.mscto.com


{


disconnect(hDbc);


closeConnection(hDbc);


hDbc = 0;


}


if(!initialize())


{


return null;


}


else


{


JdbcOdbcConnection jdbcodbcconnection = new JdbcOdbcConnection(OdbcApi, hEnv, this); 软件开发网 www.mscto.com


jdbcodbcconnection.initialize(getSubName(s), properties, DriverManager.getLoginTimeout());


jdbcodbcconnection.setURL(s);


return jdbcodbcconnection;


}


}


static


{


if(JdbcOdbcObject.isTracing())


JdbcOdbcObject.trace("JdbcOdbcDriver class loaded");


JdbcOdbcDriver jdbcodbcdriver = new JdbcOdbcDriver();


try


{


DriverManager.registerDriver(jdbcodbcdriver);


}


catch(SQLException sqlexception)


{


if(JdbcOdbcObject.isTracing())


JdbcOdbcObject.trace("Unable to register driver");


}


}


}


public interface JdbcOdbcDriverInterface

软件开发网 www.mscto.com


extends Driver


{

软件开发网 www.mscto.com


... 软件开发网 www.mscto.com


}


3 连接过程


jdbc.sql.Connection con =


DriverManager.getConnection("jdbc:odbc:pubs","sa","");


public class DriverManager {


public static synchronized 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

软件开发网 www.mscto.com


// be null.


ClassLoader callerCL = DriverManager.getCallerClassLoader();


if (user != null) {

软件开发网 www.mscto.com


info.put("user", user);


}


if (password != null) {


info.put("password", password);


}


return (getConnection(url, info, callerCL));


}


private static synchronized Connection getConnection(


String url,


java.util.Properties info,


ClassLoader callerCL) throws SQLException


{


...


Connection result = di.driver.connect(url, info);


...


}


}


源代码网推荐

源代码网供稿.
网友评论 (0)
会员中心
网络编程
本站推荐
网络编程之精华