在JAVA开发中,有时候会遇到要连接多个不同的数据库,可能一个是SQLSERVER, 另一个是Vertica.
那么我们怎么在一个ConnectionPool工具类中实现连接不同的数据库呢?
下面是代码:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
public class ConnectionPool {
private static final Logger _LOG = LoggerFactory.getLogger(ConnectionPool.class); // 用Log4J来记录日志
private static HikariDataSource pool; //定义第一个DataSource,用的是com.zaxxer.hikari.HikariDataSource
private static HikariDataSource pool1;//定义第二个DataSource,用的是com.zaxxer.hikari.HikariDataSource
//在构造函数中对DataSource进行配置,读取的是.properties文件。
private ConnectionPool() {
HikariConfig config = new HikariConfig("hikari.properties");
HikariConfig config1 = new HikariConfig("hikari1.properties");
pool = new HikariDataSource(config);
pool1 = new HikariDataSource(config1);
}
//得到第一个Instance.
public synchronized static HikariDataSource getInstance() {
if (pool == null ) {
try {
if (pool == null) {
new ConnectionPool();
}
} catch (Exception e) {
_LOG.error(e.getMessage(), e);
}
}
return pool;
}
//得到第二个Instance.
public synchronized static HikariDataSource getInstance1() {
if (pool1 == null ) {
try {
if (pool1 == null) {
new ConnectionPool();
}
} catch (Exception e) {
_LOG.error(e.getMessage(), e);
}
}
return pool1;
}
//这个是用来测试是否连接数据库成功。
public static void main(String[] args) {
String content = "helloworld" + new Random().nextInt(100);
Connection conn = null;
PreparedStatement ps = null;
try {
System.out.println("before get connection");
conn = ConnectionPool.getInstance().getConnection();
ps = conn.prepareStatement("insert into test_msmq values(?, CURRENT_TIMESTAMP)");
ps.setObject(1, content);
// String sql = "insert into dev.sai_test_msmq values (current_timestamp, '" + content + "')";
// ps = conn.prepareStatement(sql);
ps.execute();
System.out.println("success");
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
下面是hikari.properties的内容:
dataSourceClassName=com.microsoft.sqlserver.jdbc.SQLServerDataSource
#jdbcUrl=jdbc:jtds:sqlserver://servername:port;DatabaseName=xxx
dataSource.user=xxx
dataSource.password=xxx
dataSource.databaseName=xxx
dataSource.serverName=xxx
pom.xml中用到com.zaxxer.hikari的配置。
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP-java6</artifactId>
<version>2.2.5</version>
<scope>compile</scope>
</dependency>