以下代码为自己简单编写的数据库切换工具类,前提是项目已导入数据库对应的jdbc驱动。 有需自取
package com.example.multidatasources.config;
import com.example.multidatasources.constant.DataTypeEnum;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import javax.xml.crypto.Data;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
public class DataSourceConnectionConfig {
private final static String MYSQL = "mysql";
private final static String ORACLE = "oracle";
//创建数据源,连接数据源
public static Connection createDataSource(String sqlType,String url,String username,String
password){
//com.mysql.cj.jdbc.Driver
String className = DataTypeEnum.MYSQL_DRIVER.getDriver();
if (ORACLE.equals(sqlType.toLowerCase())){
//oracle.jdbc.driver.OracleDriver
className = DataTypeEnum.ORACLE_DRIVER.getDriver();
}
try {
Class cls = Class.forName(className);
Connection connection = DriverManager.getConnection(url,username,password);
return connection;
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
return null;
}
}
//查询操作
public static String executeSql(Connection connection,String sql,@Nullable Object... params){
try {
PreparedStatement preparedStatement = connection.prepareStatement(sql);
if (params.length > 0){
for (int i=1;i<=params.length;i++){
preparedStatement.setObject(i,params[i-1]);
}
}
ResultSet resultSet = preparedStatement.executeQuery();
String dataJsonString = getDataOfJsonString(resultSet,resultSet.getMetaData());
System.out.println(dataJsonString);
return dataJsonString;
} catch (SQLException e) {
e.printStackTrace();
return null;
}finally {
try {
数据库切换小练习
2019年11月11日
16:48
分区 web工具 的第 7 页
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static String getDataOfJsonString(ResultSet resultSet,ResultSetMetaData
resultSetMetaData){
Map<Integer,Map<String,Object>> dataMap = new HashMap<>();
try {
//获取结果集属性个数
int columnCount = resultSetMetaData.getColumnCount();
int count=0;
while (resultSet.next()) {
Map<String,Object> oneDataMap = new HashMap<>();
for (int i=1;i<=columnCount;i++){
//获取属性名称
String columnName = resultSetMetaData.getColumnName(i);
//获取属性对应的数据
Object columnData = resultSet.getObject(columnName);
oneDataMap.put(columnName,columnData);
}
dataMap.put(count++,oneDataMap);
}
return dataMap.toString();
}catch(SQLException e){
e.printStackTrace();
return null;
}
}
//插入数据
public static boolean insertData(Connection connection,String sql,@Nullable Object... params){
try {
PreparedStatement preparedStatement = connection.prepareStatement(sql);
if (params.length > 0){
for (int i=1;i<=params.length;i++){
preparedStatement.setObject(i,params[i-1]);
}
}
int num = preparedStatement.executeUpdate();
return num > 0 ? true : false;
} catch (SQLException e) {
e.printStackTrace();
return false;
}finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}