连接多个不同数据库
DruidDataSource
Druid是阿里巴巴开源的一款高性能的Java数据库连接池,它不仅提供了数据库连接池的功能,还包含了SQL监控、SQL防泄漏、SQL执行日志等功能,是Java应用中常用的数据库连接池之一。DruidDataSource是Druid中的核心类,用于创建和管理数据库连接。
多个数据库
包含MYSQL、ORACLE、GBASE
public enum DbTypeEnum {
MYSQL,
ORACLE,
GBASE
}
新建DataSource
包含MYSQL、ORACLE、GBASE
private static DruidDataSource getDataSource(int type) {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(MYSQL_DRIVER_6);
dataSource.setUrl("jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC");
dataSource.setUsername("root");
dataSource.setPassword("root");
if (ORACLE.ordinal() == type) {
dataSource.setDriverClassName(ORACLE_DRIVER);
// jdbc:oracle:thin@[hostname]:[port]/[DB service name]
dataSource.setUrl("jdbc:oracle:thin:@localhost:1521/FREEPDB1");
dataSource.setUsername("system");
dataSource.setPassword("root");
}
if (GBASE.ordinal() == type) {
dataSource.setDriverClassName(GBASE_DRIVER);
// jdbc:oracle:thin@[hostname]:[port]/[DB service name]
dataSource.setUrl("jdbc:gbasedbt-sqli://172.20.208.2:9088/appdev:GBASEDBTSERVER=gbase01;DB_LOCALE=zh_CN.utf8;CLIENT_LOCALE=zh_CN.utf8;IFX_LOCK_MODE_WAIT=10");
dataSource.setUsername("gbasedbt");
dataSource.setPassword("GBase123$%");
}
return dataSource;
}
测试连接
包含MYSQL、ORACLE、GBASE
private static void testDataSource(DruidDataSource dataSource, int type) {
try {
// 获取连接
Connection conn = dataSource.getConnection();
System.out.println("Connection successful!");
if (0 == type) {
PreparedStatement stmt = conn.prepareStatement("SELECT id, code, name FROM report;");
ResultSet rslt = stmt.executeQuery();
while (rslt.next()) {
System.out.println(rslt.getString(1) + " | " + rslt.getString(2)
+ " | " + rslt.getString(3));
}
}
if (1 == type) {
PreparedStatement stmt = conn.prepareStatement("SELECT id, code, name FROM ROOT.REPORT");
ResultSet rslt = stmt.executeQuery();
while (rslt.next()) {
// System.out.println(rslt.getString(1));
System.out.println(rslt.getString(1) + " | " + rslt.getString(2)
+ " | " + rslt.getString(3));
}
}
if (2 == type) {
PreparedStatement stmt = conn.prepareStatement("SELECT id, code, name FROM REPORT");
ResultSet rslt = stmt.executeQuery();
while (rslt.next()) {
// System.out.println(rslt.getString(1));
System.out.println(rslt.getString(1) + " | " + rslt.getString(2)
+ " | " + rslt.getString(3));
}
}
// 关闭连接
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
主函数
public static void main(String[] args) {
int type = GBASE.ordinal();
DruidDataSource dataSource = getDataSource(type);
// 设置初始连接数
dataSource.setInitialSize(5);
// 设置最大连接数
dataSource.setMaxActive(20);
// 设置最小空闲连接数
dataSource.setMinIdle(5);
// 测试连接池
testDataSource(dataSource, type);
dataSource.close();
}