更换数据库动态切换数据源做查询
要制作快速开发框架需要动态切换数据库做增删改查操作,本文介绍在 Springboot 2.0 中制作的工具类
package com.cc.dynamicdb.utils;
import com.cc.dynamicdb.model.DBConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @ClassName:DynamicDBUtils
* @Description:依赖类:DBConfig
* @Author:chanchaw
* @Date:2019/11/13 15:45
* @Version:1.0
**/
@Service
public class DynamicDBUtils {
/**
* 查询返回记录集
* @param dbConfig 链接数据库用到的5个参数构成的对象,例如:{ server:49.234.90.38,port:3306,dbName:atools,userName:root,userPwd:!Xdf123456 }
* @param sql 要执行的SQL语句字串,已经将参数拼接在内了,不用传查询参数进来
* @return
*/
public List
还有个依赖类
package com.cc.dynamicdb.model;
/**
* @ClassName:DBConfig
* @Description:TODO
* @Author:chanchaw
* @Date:2019/11/13 8:16
* @Version:1.0
**/
public class DBConfig {
private String server;
private int port;
private String dbName;
private String driver;
private String dbUserName;
private String dbUserPwd;
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getDbName() {
return dbName;
}
public void setDbName(String dbName) {
this.dbName = dbName;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getDbUserName() {
return dbUserName;
}
public void setDbUserName(String dbUserName) {
this.dbUserName = dbUserName;
}
public String getDbUserPwd() {
return dbUserPwd;
}
public void setDbUserPwd(String dbUserPwd) {
this.dbUserPwd = dbUserPwd;
}
@Override
public String toString() {
return "DBConfig{" +
"server='" + server + '\'' +
", port=" + port +
", dbName='" + dbName + '\'' +
", driver='" + driver + '\'' +
", dbUserName='" + dbUserName + '\'' +
", dbUserPwd='" + dbUserPwd + '\'' +
'}';
}
/**
* 构建数据库链接字串
* @return
*/
public String getUrl(){
String ret = "jdbc:mysql://" + server + ":" + port + "/" + dbName + "?userUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useLegacyDatetimeCode=false";
return ret;
}
}