首先,简单复习一下JDBC用法:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
|
com.mysql.jdbc.Driver类中的实现:
static {
try {
DriverManager.registerDriver(new Driver());
} catch (SQLException var1) {
throw new RuntimeException("Can't register driver!");
}
}
|
大致原理:
服务定义者:定义一个【服务接口】,一个【服务定义接口提供者接口】,一个注册类。
服务提供者(比如说mysql驱动包,oracle驱动包等):定义两个实现类分别实现【服务接口】和【服务定义接口提供者接口】。
下面我们以一个例子来展示JDBC的中的服务提供者框架:
//服务接口:提供具体操作
public interface Statement {
int executeUpdate(String sql);
//其他各种方法实现......
}
//服务定义接口的提供者接口:产出服务接口实现类
public interface Connection {
Statement createStatement();
}
//服务接口具体实现
public class StatementImpl implements Statement {
public int executeUpdate(String sql) {
//TODO 执行sql等等操作
System.out.println("sql语句:" + sql + " 执行完成!");
return 1;
}
//其他各种方法实现......
}
//服务定义接口的提供者接口具体实现
public class ConnectionImpl implements Connection{
public Statement createStatement() {
//继续实现Statement 判断返回
return new StatementImpl();
}
}
//具体注册类
public class DriverManager {
private static final Map<String, Connection> providers = new ConcurrentHashMap<String, Connection>();
public static void registerDriver (String name, Connection conn){
providers.put(name, conn);
}
public static Connection getConnection(String name) {
Connection conn = providers.get(name);
if (conn == null) {
throw new RuntimeException("未获取到连接!!");
}
return conn;
}
}
public class Driver {
static {
try {
DriverManager.registerDriver("jdbc:mysql://localhost:3306/demo", new ConnectionImpl());
} catch (Exception var1) {
throw new RuntimeException("Can't register Connection!");
}
}
}
//测试方法
public static void main(String[] args) throws Exception {
Class.forName("com.test.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo");
Statement statement = conn.createStatement();
statement.executeUpdate("select 1 from dual");
}
|
上面的代码可以直接copy到开发工具中运行,这里的StatementImpl和ConnectionImpl就相当于具体的数据库厂商,比如说使用musql数据库就需要导入mysql-connector-java-5.1.39.jar而jar里面就是封装了StatementImpl和ConnectionImpl,如果我换成oracle数据库,这时我只需创建另外一个jar包并重新创建实现类StatementImpl和ConnectionImpl即可。(这里只是简单介绍)。
完事,下班。