JDBC详解系列(三)之建立连接

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_37139197/article/details/78868742

  在JDBC详解系列(一)之流程中,我将数据库的连接分解成了六个步骤。

JDBC流程:
第一步:加载Driver类,注册数据库驱动;
第二步:通过DriverManager,使用url,用户名和密码建立连接(Connection);
第三步:通过Connection,使用sql语句打开Statement对象;
第四步:执行语句,将结果返回resultSet;
第五步:对结果resultSet进行处理;
第六步:倒叙释放资源resultSet-》preparedStatement-》connection。

  这一次讲的是通过DriverManager建立连接。前篇中我们讲的JDBC4.0自动加载驱动在这里找到了出处;

JDBC 4.0 Drivers must include the file META-INF/services/java.sql.Driver. This file contains the name of the JDBC drivers implementation of java.sql.Driver
  在DriverManeger的类中,找到了如下的静态代码:

 static {
        loadInitialDrivers();
        println("JDBC DriverManager initialized");
    };

 通过loadInitialDrivers()这个方法可以把类路径下所有jar包中META-INF/services/java.sql.Driver文件中定义的类加载上来,此类必须继承自java.sql.Driver。

 接着看getConnection这个方法,其描述如下:

When the method getConnection is called, the DriverManager will attempt to locate a suitable driver from amongst those loaded at initialization and those loaded explicitly using the same classloader as the current applet or application.

  就是说当调用方法getConnection时,DriverManager将尝试从初始化时加载的驱动程序和与当前applet 或应用程序相同的类加载程序显式加载驱动程序中找到合适的驱动程序。而后使用相应的URL建立连接到指定的数据库。
  在DriverManager中,有如下三个方法:

    getConnection(String url)
    getConnection(String url, Properties prop)
    getConnection(String url, String user, String password)

  每个方法中都含有URL,该数据库URL指向您的数据库的地址。这三个方法是一致的,如果是第一个方法,则需要将用户名和密码携带在url中。而第二种和第三中是最后都是将账号和密码放Properties中的。
  在三个方法中,我们都可以发现如下的代码:

java.util.Properties info = new java.util.Properties();
return (getConnection(url, info, Reflection.getCallerClass()));

  也就是说,最终调用的是getConnection(url, info, Reflection.getCallerClass())这个方法。在该方法的内部,我们可以找到如下的代码:

Connection con = aDriver.driver.connect(url, info);

  也就是,从加载的数据库驱动中,找到对应的驱动,然后使用该驱动的实现来建立连接。建立连接的函数其由数据库厂商来实现。
  在建立连接以后,就可以实现应用程序与指定的数据库进行交互了。其底层是通过socket来实现的。具体的代码我就不分析了。

猜你喜欢

转载自blog.csdn.net/weixin_37139197/article/details/78868742
今日推荐