什么是JDBC?一百个实习生和应届生一百个都说是连接和操作数据库的方法。
JDBC,也就是 Java DataBase Connectivity (Java 数据库连接),其实是由Java语言编写的一堆接口和一些class类组成的一套工具类的程序。它里面的一堆接口,都是给不同的数据库服务商定义的一套Java连接数据库的一套规则,一套规范。也就是说JDBC并不能给我们直接连接和操作数据库,真正操作数据库的,是各大数据库服务商按照JDBC规范写出来的驱动Jar包,JDBC和驱动包的关系,就是很单纯很清纯的接口与实现类的关系,修电脑与不过夜的关系。
简单看下JDBC怎么连接我本地测试数据库的:
不难看出,JDBC主要有四步操作:
1:加载数据库驱动
2:获取数据库连接
3:创建Statement/PreparedStatement
4:执行CRUD操作,封装返回结果ResultSet
下面开始讲大道理:
一:加载数据库驱动
都说了驱动Jar包,那就可以通过全限定类名通过反射方式来创建和加载。加载进来之后,在DriverManager驱动管理器中就会有一个方法registerDriver的,就会悄咪咪找上加载进来的驱动。既然是规范,那些各大数据库服务商驱动也不能乱来,都要老老实实实现一个java.sql.Driver的接口。
二:获取数据库连接
这一步会返回一个链接Connection,创建链接主要在getConnection方法,进去看。
那个被循环的是一个装满了已注册的驱动的ArrayList,以前老版本好像也是个vector
这都不是重点,我们还要继续往driver.connect方法里面看:
然后可以看到这里那么多种连接类型,各自都有什么用,创建过程是怎样,就不每个进去看了,只看最简单的ConnectionImpl通过什么创建链接
public ConnectionImpl(HostInfo hostInfo) throws SQLException {
try {
this.origHostInfo = hostInfo;
this.origHostToConnectTo = hostInfo.getHost();
this.origPortToConnectTo = hostInfo.getPort();
this.database = hostInfo.getDatabase();
this.user = StringUtils.isNullOrEmpty(hostInfo.getUser()) ? "" : hostInfo.getUser();
this.password = StringUtils.isNullOrEmpty(hostInfo.getPassword()) ? "" : hostInfo.getPassword();
this.props = hostInfo.exposeAsProperties();
this.propertySet = new JdbcPropertySetImpl();
this.propertySet.initializeProperties(this.props);
this.nullStatementResultSetFactory = new ResultSetFactory(this, (StatementImpl)null);
this.session = new NativeSession(hostInfo, this.propertySet);
this.session.addListener(this);
this.autoReconnectForPools = this.propertySet.getBooleanProperty(PropertyKey.autoReconnectForPools);
this.cachePrepStmts = this.propertySet.getBooleanProperty(PropertyKey.cachePrepStmts);
this.autoReconnect = this.propertySet.getBooleanProperty(PropertyKey.autoReconnect);
this.useUsageAdvisor = this.propertySet.getBooleanProperty(PropertyKey.useUsageAdvisor);
this.reconnectAtTxEnd = this.propertySet.getBooleanProperty(PropertyKey.reconnectAtTxEnd);
this.emulateUnsupportedPstmts = this.propertySet.getBooleanProperty(PropertyKey.emulateUnsupportedPstmts);