Java 使用 JDBC 连接数据库的代码整合[MySql、SqlServer、Oracle]-[经过设计模式改造](2020年寒假小目标01)

时间:2021-10-12 21:00:05

日期:2020.01.08

博客期:121

星期三

  今天对过去整个大二和大三上半学期用到的数据库的方法进行汇总,可以有效的使用、套用,每一个部分都有《软件设计模式》知识,上述代码满足了开闭原则,如果要使用此代码,只需添加数据类继承已经写好的类就可以了,无需修改。  

  开发项目中,项目整体结构:

Java 使用 JDBC 连接数据库的代码整合[MySql、SqlServer、Oracle]-[经过设计模式改造](2020年寒假小目标01)

  类图:

Java 使用 JDBC 连接数据库的代码整合[MySql、SqlServer、Oracle]-[经过设计模式改造](2020年寒假小目标01)

  源码:

    com包:

      com.dblink包:

        com.dblink.basic包:

 package com.dblink.basic;

 import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; public class SqlConnection {
//---[基础数据]
public Connection conn;
public Statement stmt;
public ResultSet rs;
//---[方法区]
//构造方法
public SqlConnection() {
this.conn = null;
this.stmt = null;
this.rs = null;
}
public SqlConnection(Connection conn) {
this.conn = conn;
this.stmt = null;
this.rs = null;
}
public void close() {
try {
if(this.rs!=null) {
this.rs.close();
}
if(this.stmt!=null)
this.stmt.close();
if(this.conn!=null)
this.conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

SqlConnection.java

          com.dblink.basic.utils包:

 package com.dblink.basic.utils;

 import com.dblink.basic.SqlConnection;

 import java.sql.Connection;
import java.sql.SQLException; public interface DBUtils {
public SqlConnection getSQLConnection() throws SQLException, ClassNotFoundException;
}

DBUtils.java

 package com.dblink.basic.utils;

 import com.dblink.basic.SqlConnection;
import com.dblink.basic.utils.sqlKind.Sql;
import com.dblink.basic.utils.user.UserInfo; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException; public class SqlUtils implements DBUtils{
//---[属性成员]
private Sql sqlInfo;
private UserInfo userInfo;
//---[方法成员]
private Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName(sqlInfo.getDriver());
Connection conn = null;
if(userInfo==null)
conn = DriverManager.getConnection(sqlInfo.buildURL());
else
conn = DriverManager.getConnection(sqlInfo.buildURL(),userInfo.getUsername(),userInfo.getPassword()); return conn;
}
public SqlConnection getSQLConnection() throws SQLException, ClassNotFoundException {
return new SqlConnection(getConnection());
}
/*构造方法*/
public SqlUtils(Sql sqlInfo,UserInfo userInfo){
this.sqlInfo = sqlInfo;
this.userInfo = userInfo;
}
}

SqlUtils.java

            com.dblink.basic.utils.sqlKind包:

 package com.dblink.basic.utils.sqlKind;

 /*标准信息连接类*/
public abstract class Sql {
//---[属性成员]
/*端口*/
protected String port = "";
/*端口*/
protected String database = "";
/*主机地址*/
protected String host = "";
//---[方法成员]
/*获取连接 URL*/
public abstract String buildURL();
/*获得相应数据库给定的驱动*/
public abstract String getDriver();
/*get、set方法*/
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public String getDatabase() {
return database;
}
public void setDatabase(String database) {
this.database = database;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
/*构造方法*/
public Sql(String database,String port) {
this.port = port;
this.database = database;
this.host = "localhost";
}
public Sql(String database,String port,String host) {
this.port = port;
this.database = database;
this.host = host;
}
}

Sql.java

 package com.dblink.basic.utils.sqlKind;

 public class SqlServer extends Sql{
//---[方法成员]
/*构造方法*/
public SqlServer(String database) {
super(database, "1433");
}
public SqlServer(String database, String port) {
super(database, port);
}
public SqlServer(String database, String port,boolean is) {
super(database, port);
}
public SqlServer(String database, boolean is,String host) {
super(database, "1433", host);
}
public SqlServer(String database, String port, String host) {
super(database, port, host);
}
/*获取连接 URL*/
@Override
public String buildURL() {
return "jdbc:sqlserver://"+host+":"+port+";DatabaseName="+database+";";
}
/*获得相应数据库给定的驱动*/
@Override
public String getDriver() {
return "com.microsoft.sqlserver.jdbc.SQLServerDriver";
}
}

SqlServer.java

 package com.dblink.basic.utils.sqlKind;

 public class Oracle extends Sql {
//---[方法成员]
/*构造方法*/
public Oracle(String database) {
super(database, "1521");
}
public Oracle(String database, String port) {
super(database, port);
}
public Oracle(String database, String port,boolean is) {
super(database, port);
}
public Oracle(String database, boolean is,String host) {
super(database, "1521", host);
}
public Oracle(String database, String port, String host) {
super(database, port, host);
}
/*获取连接 URL*/
@Override
public String buildURL() {
return "jdbc:oracle:thin:@"+host+":"+port+":"+database;
}
/*获得相应数据库给定的驱动*/
@Override
public String getDriver() {
return "oracle.jdbc.OracleDriver";
}
}

Oracle.java

 package com.dblink.basic.utils.sqlKind;

 public class MySql extends Sql{
//---[方法成员]
/*构造方法*/
public MySql(String database) {
super(database, "3306");
}
public MySql(String database, String port) {
super(database, port);
}
public MySql(String database, String port,boolean is) {
super(database, port);
}
public MySql(String database, boolean is,String host) {
super(database, "3306", host);
}
public MySql(String database, String port, String host) {
super(database, port, host);
}
/*获取连接 URL*/
@Override
public String buildURL() {
return "jdbc:mysql://"+host+":"+port+"/"+database+"?useSSL=false&serverTimezone=UTC";
}
/*获得相应数据库给定的驱动*/
@Override
public String getDriver() {
return "com.mysql.jdbc.Driver";
}
}

MySql.java

 package com.dblink.basic.utils.sqlKind;

 public class MySql_s extends MySql{
//---[方法成员]
/*构造方法*/
public MySql_s(String database) {
super(database);
}
public MySql_s(String database, String port) {
super(database, port);
}
public MySql_s(String database, String port, boolean is) {
super(database, port, is);
}
public MySql_s(String database, boolean is, String host) {
super(database, is, host);
}
public MySql_s(String database, String port, String host) {
super(database, port, host);
}
/*获得相应数据库给定的驱动*/
@Override
public String getDriver() {
return "com.mysql.cj.jdbc.Driver";
}
}

MySql_s.java

 package com.dblink.basic.utils.sqlKind;

 public class WindowsSqlServer extends SqlServer {
//---[方法成员]
/*构造方法*/
public WindowsSqlServer(String database) {
super(database);
}
public WindowsSqlServer(String database, String port) {
super(database, port);
}
public WindowsSqlServer(String database, String port, boolean is) {
super(database, port, is);
}
public WindowsSqlServer(String database, boolean is, String host) {
super(database, is, host);
}
public WindowsSqlServer(String database, String port, String host) {
super(database, port, host);
}
/*获取连接 URL*/
@Override
public String buildURL() {
return "jdbc:sqlserver://"+host+":"+port+";integratedSecurity=true;DatabaseName="+database+";";
}
}

WindowsSqlServer.java

            com.dblink.basic.utils.user包:

 package com.dblink.basic.utils.user;

 //登录成员类
public class UserInfo {
//---[属性成员]
private String username;
private String password;
//---[方法成员]
/*set、get方法*/
//set
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
//get
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
/*构造方法*/
public UserInfo(String username,String password){
this.username = username;
this.password = password;
}
/*检验*/
@Override
public String toString(){
return username+","+password;
}
}

UserInfo.java

        com.dblink.bean包:

 package com.dblink.bean;

 import org.json.JSONArray;
import org.json.JSONObject; import java.util.ArrayList;
import java.util.Collection; public class JavaBean extends ArrayList<Object> {
//---[方法区]
//构造方法
public JavaBean() {
super();
}
public JavaBean(Collection<Object> c) {
super(c);
}
public JavaBean(int initialCapacity) {
super(initialCapacity);
}
//转化方法
public String toString(){
return super.toString();
}
public JSONArray toJSONArray(){
JSONArray jsonArray = new JSONArray();
int leng = super.size();
for(int i=0;i<leng;++i){
Object q = super.get(i);
jsonArray.put(q);
}
return jsonArray;
}
}

JavaBean.java

 package com.dblink.bean;

 import org.json.JSONArray;

 import java.util.ArrayList;
import java.util.Collection; public class BeanGroup extends ArrayList <JavaBean> {
//---[方法区]
//构造方法
public BeanGroup(int initialCapacity) {
super(initialCapacity);
}
public BeanGroup() {
super();
}
public BeanGroup(Collection<JavaBean> c) {
super(c);
}
//转化方法
public String toString(){
return super.toString();
}
public JSONArray toJSONArray(){
JSONArray jsonArray = new JSONArray();
int leng = super.size();
for(int i=0;i<leng;++i){
JavaBean jb = super.get(i);
jsonArray.put(jb.toJSONArray());
}
return jsonArray;
}
}

BeanGroup.java

 package com.dblink.bean;

 import org.json.JSONArray;
import org.json.JSONObject; public class ReadableTable {
//---[属性成员]
//列名称集合
public JavaBean cloName;
//表格详细信息
public BeanGroup beans;
//---[方法成员]
/*构造方法*/
public ReadableTable(){
this.cloName = null;
this.beans = null;
}
public ReadableTable(JavaBean cloName,BeanGroup beans){
this.cloName = cloName;
this.beans = beans;
}
/*格式转化*/
public JSONObject toJSONObject(){
JSONObject jsonObject = new JSONObject();
jsonObject.put("Length",this.beans.size());
jsonObject.put("Column",this.cloName.size());
jsonObject.put("cloName",this.cloName.toJSONArray());
jsonObject.put("beans",this.beans.toJSONArray());
return jsonObject;
}
public JSONArray toJSONArray(){
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
int leng = this.beans.size();
int cloNum = this.cloName.size();
jsonObject.put("Length",leng);
jsonObject.put("Column",cloNum);
jsonObject.put("ColNames",this.cloName.toJSONArray());
jsonArray.put(jsonObject);
for (int i=0;i<leng;++i)
{
JSONObject jso = new JSONObject();
JavaBean jb = this.beans.get(i);
for(int j=0;j<cloNum;++j)
{
Object obj = jb.get(j);
String name = this.cloName.get(j).toString();
jso.put(name,obj);
}
jsonArray.put(jso);
}
return jsonArray;
}
}

ReadableTable.java

        com.dblink.sql包:

 package com.dblink.sql;

 import com.dblink.basic.SqlConnection;
import com.dblink.basic.utils.DBUtils;
import com.dblink.bean.BeanGroup;
import com.dblink.bean.JavaBean;
import com.dblink.bean.ReadableTable; import java.sql.PreparedStatement;
import java.sql.ResultSetMetaData;
import java.sql.SQLException; /*数据库连接中介者*/
public class DBLink {
//---[基础数据]
//连接信息
protected SqlConnection sqlConnection = null;
//---[方法区]
//构造方法
public DBLink(DBUtils dbUtils){
buildConnection(dbUtils);
}
//建立连接
protected void buildConnection(DBUtils dbUtils) {
try {
this.sqlConnection = dbUtils.getSQLConnection();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
//重新设置连接
public void reset(){
try {
if(this.sqlConnection.rs!=null)
this.sqlConnection.rs.close();
if(this.sqlConnection.stmt!=null)
this.sqlConnection.stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//获取查询结果
public ReadableTable getSelect(String sql) throws SQLException{
ReadableTable rt = new ReadableTable();
BeanGroup bg = new BeanGroup();
JavaBean jb = new JavaBean(); reset();
this.sqlConnection.stmt = this.sqlConnection.conn.createStatement();
this.sqlConnection.rs = this.sqlConnection.stmt.executeQuery(sql); ResultSetMetaData resultSetMetaData = this.sqlConnection.rs.getMetaData(); int leng = resultSetMetaData.getColumnCount(); for(int i=1;i<=leng;++i)
{
String name = resultSetMetaData.getColumnName(i);
jb.add(name);
} while(this.sqlConnection.rs.next())
{
JavaBean jbs = new JavaBean();
for(int j=1;j<=leng;++j)
{
String cn = resultSetMetaData.getColumnName(j);
jbs.add(this.sqlConnection.rs.getObject(cn));
}
bg.add(jbs);
} rt.beans = bg;
rt.cloName = jb; return rt;
}
//执行操作语句
public void executeSql(String sql){
try {
reset();
this.sqlConnection.stmt = this.sqlConnection.conn.createStatement();
this.sqlConnection.stmt = (PreparedStatement) this.sqlConnection.conn.prepareStatement(sql);
((PreparedStatement)sqlConnection.stmt).executeUpdate();
this.sqlConnection.stmt.close();
} catch (SQLException e) {
System.out.println("爷爷!你的数据库连接出现问题啦!");
}
}
//释放连接
public void free(){
this.sqlConnection.close();
}
}

DBLink.java

 package com.dblink.sql;

 import com.dblink.basic.utils.DBUtils;

 /*可储存连接信息的数据库连接中介者*/
public class RoyalDBLink extends DBLink {
protected DBUtils dbUtils = null;
public RoyalDBLink(DBUtils dbUtils) {
super(dbUtils);
this.dbUtils = dbUtils;
}
public DBUtils getSqlUtils(){
return this.dbUtils;
}
}

RoyalDBLink.java

    然后是测试类:com.dblink.sql 包内 

 package com.dblink.sql;

 import com.dblink.basic.SqlUtils;
import com.dblink.basic.sqlKind.MySql_s;
import com.dblink.basic.sqlKind.Oracle;
import com.dblink.basic.sqlKind.WindowsSqlServer;
import com.dblink.basic.utils.UserInfo; import java.sql.SQLException; public class DBTest {
public static void main(String[] args) throws SQLException { //测试 1
//使用MySql数据库,使用用户登录模式
DBLink dbLink1 = new DBLink(new SqlUtils(new MySql_s("hebei"),new UserInfo("root","cdhbhbgbjzdz")));
System.out.println(dbLink1.getSelect("Select * From tree").toJSONObject());
dbLink1.free(); //测试 2
//使用SqlServer数据库(Windows验证模式)
DBLink dbLink2 = new DBLink(new SqlUtils(new WindowsSqlServer("bookMis"),null));
System.out.println(dbLink2.getSelect("Select * From book").beans.toJSONArray());
dbLink2.free(); //测试 3
//使用Oracle数据库,使用用户登录模式
DBLink dbLink3 = new DBLink(new SqlUtils(new Oracle("ORACLE"),new UserInfo("SCOTT","cdbhbgbjzdz")));
System.out.println(dbLink3.getSelect("Select * From T_USER").beans.toJSONArray());
dbLink3.free(); }
}

DBTest.jaa

    PS:

      这里补充一下:连接每一种数据库需要的驱动都不一样

      小编使用IDEA编写的Java程序(JDK版本为1.8,也就是8),SqlServer安装了2012版本,对应的Jar包如下:(外部依赖项)

      Java 使用 JDBC 连接数据库的代码整合[MySql、SqlServer、Oracle]-[经过设计模式改造](2020年寒假小目标01)

      对应下载地址:(请根据自己下载的数据库版本选择相应的驱动Jar包)

        Mysql:https://dev.mysql.com/downloads/connector/j/

        SqlServer:https://www.microsoft.com/zh-CN/download/details.aspx?displaylang=en&id=11774

        Oracle:https://www.oracle.com/database/technologies/appdev/jdbc.html

      如果上述链接失效,可以采用百度搜索 “【数据库名称】 驱动  官网   下载 ”的检索式进行检索

      注:如果你要选择SqlServer的Windows验证模式,请你一定要安装驱动并从官网解压下来的压缩包内找到 sqljdbc_auth.dll 文件,把它复制到 C:\Windows\System32 目录下(Linux系统的无法使用windows验证,算是废话吧)

  分析用到的设计模式:

    1、建造者模式:对Connection的创建是由外类的方法创建的,创建过程不对外部实体进行公开。

    2、桥接模式:将原本的连接信息拆分成UserInfo和Sql两部分,是对“数据库“部分的抽象化和”登录“部分的抽象化的分离,满足接口隔离原则。

    3、策略模式:将数据库具体构建的方法封装起来,程序员调用时可以根据不同数据库的需要选择不同的策略。

    4、模板方法模式:这个在未拆分的原数据库连接类中就已经实现了,具体实现在DBLink类当中。

    5、备忘录模式:RoyalDBLink类是对DBLink类的备忘记录类,不像DBLink只要连接建立之后,就已经丢失了连接信息。

    6、中介者模式:ReadableTable类是数据和DBLink的中介者,起到了协调使用的左右(ReadableTable是索取了本次索引的包括列名和全体数据的集合)。

    至于外观模式,我平常一直都在用就觉得没什么说的必要了。

   设计细节:

    最后我没有让 SqlUtils 类 和 DBUtils 接口 划泛化关系,这是因为SqlUtils作为建造者(Builder),不应该对外展示自己的建造方法只需要返回需要的成员就好(接口的方法都是公用的,不符合本程序设计思想的需要),但是我又找到了public部分,将原来的代码改为了getSqlConnection的方法,这样就可以针对接口编程了!