很多时候我们需要使用到多数据源,那么在动态配置多数据源的时候就需要先验证数据库是否连接有效。
package com.shucha.deveiface.biz.test;
import com.shucha.deveiface.biz.model.DbSource;
import java.sql.DriverManager;
import java.util.List;
/**
* @author tqf
* @Description
* @Version 1.0
* @since 2020-09-18 09:59
*/
public class TestDatasource {
public static void main(String[] args) {
String username = ""; //用户名
String password = "";//密码
String dbName = ""; //数据库名
Integer dbType = 3; //数据库类型 1-mysql,2-oracle,3-postgressql
String dbIp =""; //数据库地址
String dbPort = ""; //端口
String dbIpPort = dbIp + ":" + dbPort;
String driveClass;
String jdbcUrl;
try {
switch (dbType) {
case 1:
// mysql数据库
driveClass = "com.mysql.cj.jdbc.Driver";
jdbcUrl = "jdbc:mysql://" + dbIpPort + "/" + dbName
+ "?serverTimezone=Asia/Shanghai&serverTimezone=Asia/Shanghai" +
"&useSSL=false&useUnicode=true&characterEncoding=UTF-8";
break;
case 2:
// oracle数据库
driveClass = "oracle.jdbc.OracleDriver";
jdbcUrl = "jdbc:oracle:thin:@" + dbIpPort + ":" + dbName;
break;
default:
// PostgreSQL数据库
driveClass = "org.postgresql.Driver";
jdbcUrl = "jdbc:postgresql://" + dbIpPort + "/" + dbName;
}
boolean b = testDatasource(driveClass,jdbcUrl,username,password);
System.out.println(b);
}catch (Exception e){
}
}
//测试数据源连接是否有效
public static boolean testDatasource(String driveClass,String url,String username,String password){
try {
Class.forName(driveClass);
DriverManager.getConnection(url, username, password);
return true;
} catch (Exception e) {
return false;
}
}
}