Jdbc源码分析及桥接模式
Jdbc源码分析及桥接模式
说起jdbc,我相信很多⼈都不陌⽣,在最开始的web项⽬中,我们常常⽤它来连接数据库执⾏sql语句,下⾯是⼀个连接mysql的例⼦:
/**
*    定义数据库连接辅助类
*/
public class DBhelper {
private static final String DRIVERNAME = "sql.cj.jdbc.Driver";
private static final String URL = "jdbc:mysql://127.0.0.1:3306/test";
private static final String USER = "root";
private static final String PASSWORD = "123456";鱼粉最新价格
private Connection conn = null;
private Statement st = null;
private PreparedStatement ppst = null;
private ResultSet rs = null;
/*加载驱动*/
static {
try {
Class.forName(DRIVERNAME).newInstance();
悄无声息的近义词
} catch (Exception e) {
e.printStackTrace();
System.out.println("加载驱动失败");
}
}
/*获取数据库连接*/
public Connection getConn(){
try {
conn = Connection(URL,USER,PASSWORD);
} catch (SQLException throwables) {
throwables.printStackTrace();
System.out.println("获取数据库连接失败");
}
return conn;
}
/
*释放数据库连接*/
public void releaseConn(){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
System.out.Message());
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
System.out.Message());
}
}
if(ppst!=null){
try {
ppst.close();
} catch (SQLException e) {
System.out.Message());
}
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
System.out.Message());
}
}
}
测试⼀下:
public class TestJdbc {
private Connection conn = null;
private Statement st = null;
private PreparedStatement ppst = null;
private ResultSet rs = null;
private List<Object> selectUser(User user){
List<Object> list = new ArrayList<>();
DBhelper dBhelper = new DBhelper();
conn = Conn();
String sql = "select * from blog_user where login_num="+LoginNum()+" and password ="+Password();        try {
st = ateStatement();
rs = st.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = ColumnCount();
while (rs.next()){
Map map = new HashMap();
for (int i = 1;i <= columnCount;i++){
map.ColumnLabel(i),rs.getObject(i));
}
list.add(map);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
}
return list;
}
public static void main(String[] args) {
TestJdbc testJdbc = new TestJdbc();
User user = new User();
user.setLoginNum(123456);
user.setPassword("123456");
List list = testJdbc.selectUser(user);
}
}
debug⼀下:
然⽽在实际开发中,我们常常⽤到的框架是mybatis,其实mybatis就是对jdbc的封装,在我们以后的开发中我们可能会遇到关于持久层的各种问题,我们理解了jdbc的原理,那么mybatis⼜有何难?
依然以mysql为例,⾸先,我们来看数据库驱动Driver的加载过程:
在上⾯的贴出的代码中,我们可以看到⼀个静态代码块,利⽤class.forName()加载这个驱动,如下图:
private static final String DRIVERNAME = "sql.cj.jdbc.Driver";
/*加载驱动*/
static {
try {
Class.forName(DRIVERNAME).newInstance();
} catch (Exception e) {
e.printStackTrace();
System.out.println("加载驱动失败");
}
祝老师元旦快乐的句子}
我们点进这个驱动,发现它继承了⼀个⽗类,实现了⼀个接⼝,⾥⾯有⼀个⽅法----注册驱动, 如下图:
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
public Driver() throws SQLException {
}
static {
try {
} catch (SQLException var1) {
throw new RuntimeException("Can't register driver!");
烤鸡翅的做法
}
}
}
我们先来看⽗接⼝ Driver,如下图:
这是⼀个顶层接⼝(由于太长,注释删掉⼀部分),简单理解⼀下注释,我们就会明⽩,这是⼀个所有的驱动必须实现的⽅法,也就是说,这是⼀个java连接数据库的⼀个接⼝,⼀个规范,数据库有很多种,因此数据库驱动也分很多种,但是不管你是那种数据库驱动,必须都要实现这个接⼝,遵循这个规范,才能连接数据库,⽆疑给我们带来了很⼤的⽅便,更换数据库就代表着更换驱动,⽽所有驱动都实现了这个接⼝,那我们只需要在利⽤反射加载驱动的class.forName()⽅法中注明需要加载的驱动就ok了,这样就可以适配所有的数据库.
高级经济师报考条件/**
* The interface that every driver class must implement.
* <P>The Java SQL framework allows for multiple database drivers.
*
* <P>Each driver should supply a class that implements
* the Driver interface.
*
* <P>The DriverManager will try to load as many drivers as it can廿怎么读
* find and then for any given connection request, it will ask each
* driver in turn to try to connect to the target URL.
*
* <P>It is strongly recommended that each Driver class should be
* small and standalone so that the Driver class can be loaded and
* queried without bringing in vast quantities of supporting code.
*
* <P>When a Driver class is loaded, it should create an instance of
* itself and register it with the DriverManager. This means that a
* user can load and register a driver by calling:
* <p>
* {@code Class.forName("foo.bah.Driver")}
*/
public interface Driver {
/**
* Attempts to make a database connection to the given URL.
* The driver should return "null" if it realizes it is the wrong kind
* of driver to connect to the given URL.  This will be common, as when
* the JDBC driver manager is asked to connect to a given URL it passes
* the URL to each loaded driver in turn.
*
*/
Connection connect(String url, java.util.Properties info)
throws SQLException;
/**
* Retrieves whether the driver thinks that it can open a connection
* to the given URL.  Typically drivers will return <code>true</code> if they
* understand the sub-protocol specified in the URL and <code>false</code> if
* they do not.
*/
boolean acceptsURL(String url) throws SQLException;
DriverPropertyInfo[] getPropertyInfo(String url, java.util.Properties info)
throws SQLException;
int getMajorVersion();
int getMinorVersion();
boolean jdbcCompliant();
public Logger getParentLogger() throws SQLFeatureNotSupportedException;
}
再看NonRegisteringDriver类
它实现了Driver,实际上,它是mysql驱动的⼀部分,⾥⾯的⼀些⽅法是关于连接mysql数据库的⼀些配置细节,根据⼀些连接属性创建⼀个真正连接数据库的⽹络通道
public class NonRegisteringDriver implements Driver {
public static String getOSName() {
return Constants.OS_NAME;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。