当前位置:天才代写 > tutorial > JAVA 教程 > Java连结数据库黑幕

Java连结数据库黑幕

2017-11-11 08:00 星期六 所属: JAVA 教程 浏览:386

副标题#e#

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
 {
  ...
 }


#p#副标题#e#

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连结数据库内幕

 

    关键字:

天才代写-代写联系方式