今天看jdk中rt.jar包中,java.sql包,大体上明白了,jdbc是sun公司发布的一套数据库实现标准,只提供接口,不具体实现。具体的实现过程由各数据库开发厂商决定。各数据库开发厂商需要提供一个用于实现上述接口的.jar包。
这样做得好处是,如果有一天变更数据库(如从sqlserver转换成为oracle数据库),只需要更改java程序中的数据库驱动程序,和将sqljdbc.jar更改为oracle提供的.jar包就可以了。当然,如果使用了oracle不识别的函数,再改一下函数就就可以了。不用修正java代码。因为java代码中不使用具体的数据库开发厂商实现的类,而是使用java.sql中定义的接口。真是太方便了。
java.sql包中主要的类和接口包括:
- 1.Connection接口,定义为:public interface Connection
- 2.Driver接口,定义为:public interface Driver
- 3.DriverManager类,定义为:public class DriverManager
- 4.PreparedStatement接口,定义为:public interface PreparedStatement extends Statement
- 5.ResultSet接口,定义为:public interface ResultSet
- 6.SQLException类,定义为:public class SQLException extends java.lang.Exception
- 7.Statement接口,定义为:public interface Statement
我们在没有任何数据库框架(如mybatis或者jpa)的时候,一般原始的连接jdbc的步骤是:
- 1.加载数据库驱动程序
- 2.连接数据
- 3.执行SQL语句,并返回执行状态和查询结果
- 4.关闭数据库连接
而针对于mybatis这类的数据库框架,他们只是将这个过程包装起来。我们去看mybatis的源码可以看到,在数据源类中,也有加载数据库驱动的操作,也有获取连接的操作等,这些步骤必不可少。然后mybatis在此基础上提供了很多自己的特性。
import java.sql.*;
public class TestDBConnection {
public static void main(String[] args) {
try {
//定义一个连接
Connection con;
//加载各数据库开发厂商实现的JDBC驱动程序
//mysql的场合:com.mysql.jdbc.Driver
Class.forName("com.mysql.jdbc.Driver");
//连接数据库(各数据库开发厂商不同)
//以下两种写法都可以(对于mysql来说)
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","sa");
//con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?user=root&password=sa");
//创建Statement对象或者PreparedStatement对象
//Statement:一般的Statement对象
//PreparedStatement:用于动态SQL的Statement对象
Statement st = con.createStatement();
String sql = "select * from table1 order by id";
//定义ResultSet对象
//执行SQL操作(查询,更新)
//executeQuery:查询
//executeUpdate:更新
//execute:一般不使用
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
//根据列索引取得数据
System.out.println(rs.getString(1));
//根据列名取得数据
System.out.println(rs.getString("columnName"));
}
//关闭资源
if (rs != null) rs.close();
if (st != null) st.close();
if (con != null) con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}