jdbc.sql.Driver d = (Driver)Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); jdbc.sql.Connection con = DriverManager.getConnection("jdbc:odbc:pubs","sa","");
你已经熟悉上面的句子了。 但是数据库到底是怎么连接的呢?:-)
java.在sql包里 java.sql.Driver, jdbc.sql.为程序开发人员提供统一的开发接口,数据库提供商提供相应的实现,只要程序开发人员知道这些接口的方法,但我们可以更深入 看看里面做了什么, 还可以学习编程模式(如Interface模式等)1 Class.forName(String classname) 的源码为:public finalclass Class implements java.io.Serializable {...public static Class forName(String className) 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 */ public synchronized Connection connect(String s, Properties properties) throws SQLException { if(JdbcOdbcObject.isTracing()) JdbcOdbcObject.trace("*Driver.connect (" + s + ")"); if(!acceptsURL(s)) return null; if(hDbc !acceptsURL(s)) return null; if(hDbc != 0) { disconnect(hDbc); closeConnection(hDbc); hDbc = 0; } if(!initialize()) { return null; } else { JdbcOdbcConnection jdbcodbcconnection = new JdbcOdbcConnection(OdbcApi, hEnv, this); 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 extends Driver{ ...}
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 // 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));}private static synchronized Connection getConnection( String url, java.util.Properties info, ClassLoader callerCL) throws SQLException {...Connection result = di.driver.connect(url, info);...} } 4 结构图:请点击查看 结构图 http://jdeveloper.myrice.com/doc/jdbc/images/howjdbc.jpg
![](/images/780-200-2.jpg)