服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

java连结数据库内幕


  java.sql包中的 java.sql.driver, jdbc.sql.connection等提供给程序开发人员统一的开发接口,数据库提供商提供相应的实现,对程序开发人员来讲只要知道这些接口都有哪些方法就可以了。但我们可以深入一些看看到底这里面都做了那些事, 同时也可以学习其中的编程模式(如interface模式等)。
  1、 class.forname(string classname) 的源码为:
  public final
  class 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 != 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 结构图:
  java连结数据库内幕

扫描关注微信公众号