Java创建连接池连接不同数据库



/**
* 数据库连接配置信息类
* @author Damon
*/
public class JdbcUrl
{ /** 定义数据库参数 */ // 数据库类型
private String DBType;
// 数据库服务器IP
private String IP;
// 数据库服务器端口
private String Port;
// 数据库名称
private String DBName;
// 用户名
private String UserName;
// 密码
private String PassWord; /**
* 默认构造方法,连接默认数据库
*/
public JdbcUrl()
{
// TODO Auto-generated constructor stub
DBType = SysCon.DATABASE_TYPE_MYSQL;
IP = "127.0.0.1";
DBName = "mysql";
Port = "3306";
UserName = "damon";
PassWord = "damon";
} /**
* 连接指定数据库
* @param urlType 传入连接类型标识
*/
public JdbcUrl(String urlType)
{
if ("mysql".equals(urlType))
{
DBType = SysCon.DATABASE_TYPE_MYSQL;
IP = "127.0.0.1";
DBName = "mysql";
Port = "3306";
UserName = "damon";
PassWord = "damon";
}
} /**
* 获取连接句柄
* @return String
*/
public String getJdbcUrl()
{
String sUrl = ""; if (DBType.trim().toUpperCase().equals("MYSQL"))
{
sUrl = "jdbc:mysql://" + IP + ":" + Port + "/" + DBName;
}
else if (DBType.trim().toUpperCase().equals("DB2"))
{
sUrl = "jdbc:db2://" + IP + ":" + Port + "/" + DBName;
} else if (DBType.trim().toUpperCase().equals("ORACLE"))
{
sUrl = "jdbc:oracle:thin:@" + IP + ":" + Port + ":" + DBName;
} else if (DBType.trim().toUpperCase().equals("SQLSERVER"))
{
sUrl = "jdbc:microsoft:sqlserver://" + IP + ":" + Port + ";databaseName=" + DBName + ";selectMethod=cursor";
}
else if (DBType.trim().toUpperCase().equals("WEBLOGICPOOL"))
{
sUrl = "jdbc:weblogic:pool:" + DBName;
}
else
{
System.out.println("暂无对应数据库驱动");
}
return sUrl;
} // getters and setters public String getDBType()
{
return DBType;
} public void setDBType(String dBType)
{
DBType = dBType;
} public String getIP()
{
return IP;
} public void setIP(String iP)
{
IP = iP;
} public String getPort()
{
return Port;
} public void setPort(String port)
{
Port = port;
} public String getDBName()
{
return DBName;
} public void setDBName(String dBName)
{
DBName = dBName;
} public String getUserName()
{
return UserName;
} public void setUserName(String userName)
{
UserName = userName;
} public String getPassWord()
{
return PassWord;
} public void setPassWord(String passWord)
{
PassWord = passWord;
} }
2、重写一个Connection类,实现Connection接口的方法,同时连接数据库。

**
* 数据库连接类,连接数据库
* @author Damon
*/
public class DBConn implements Connection
{ // 获取JdbcUrl信息
private JdbcUrl JUrl; // 数据库连接
private Connection con = null; // 连接是否已使用
private boolean bNotInUse; private CharArrayWriter m_buf = new CharArrayWriter(); private PrintWriter m_pw = new PrintWriter(m_buf, true); // 默认连接
public DBConn()
{
// TODO Auto-generated constructor stub
this.JUrl = new JdbcUrl();
} // 指定数据库连接
public DBConn(String urlType)
{
this.JUrl = new JdbcUrl(urlType);
} // 创建连接
public boolean createConnection()
{ // 根据数据库类型加载驱动及连接
try
{
// 连接MySQL数据库
if (SysCon.DATABASE_TYPE_MYSQL.equals(JUrl.getDBType()))
{
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver"); // 尝试连接数据库
con = DriverManager.getConnection(JUrl.getJdbcUrl(), JUrl.getUserName(), JUrl.getPassWord());
}
// 其他数据库类型判断及处理
// SQLSERVER
else if (SysCon.DATABASE_TYPE_SQLSERVER.equals(JUrl.getDBType()))
{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
con = DriverManager.getConnection(JUrl.getJdbcUrl(), JUrl.getUserName(), JUrl.getPassWord());
}
// DB2
else if (SysCon.DATABASE_TYPE_DB2.equals(JUrl.getDBType()))
{
Class.forName("com.ibm.db2.jcc.DB2Driver");
con = DriverManager.getConnection(JUrl.getJdbcUrl(), JUrl.getUserName(), JUrl.getPassWord());
}
// ORACLE
else if (SysCon.DATABASE_TYPE_ORACLE.equals(JUrl.getDBType()))
{
Class.forName("oracle.jdbc.driver.OracleDriver");
// 一个是缓存取到的记录数,一个是设置默认的批量提交数
Properties props = new Properties();
props.setProperty("user", JUrl.getUserName());
props.setProperty("password", JUrl.getPassWord());
props.setProperty("defaultRowPrefetch", "50");
props.setProperty("defaultExecuteBatch", "50");
con = DriverManager.getConnection(JUrl.getJdbcUrl(), props);
}
else
{
System.out.println("未匹配到数据库类型!");
return false;
} }
catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
System.out.println("加载驱动失败!");
e.printStackTrace();
return false;
}
catch (SQLException e)
{
// TODO Auto-generated catch block
System.out.println("创建连接失败..." + e.getMessage());
e.printStackTrace();
return false;
}
return true;
} protected void setInUse()
{
/**
* Record stack information when each connection is get We reassian
* System.err, so Thread.currentThread().dumpStack() can dump stack info
* into our class FilterPrintStream.
*/
new Throwable().printStackTrace(m_pw); bNotInUse = false; /**
* record lastest access time
*/
} /* 下面都是 实现Connection的方法,返回conn的实现 */
public <T> T unwrap(Class<T> iface) throws SQLException
{
// TODO Auto-generated method stub
return con.unwrap(null);
} public boolean isWrapperFor(Class<?> iface) throws SQLException
{
// TODO Auto-generated method stub
return false;
} public Statement createStatement() throws SQLException
{
// TODO Auto-generated method stub
return con.createStatement();
} public PreparedStatement prepareStatement(String sql) throws SQLException
{
// TODO Auto-generated method stub
return con.prepareStatement(sql);
} public CallableStatement prepareCall(String sql) throws SQLException
{
// TODO Auto-generated method stub
return con.prepareCall(sql);
} public String nativeSQL(String sql) throws SQLException
{
// TODO Auto-generated method stub
return con.nativeSQL(sql);
} public void setAutoCommit(boolean autoCommit) throws SQLException
{
// TODO Auto-generated method stub
con.setAutoCommit(autoCommit);
} public boolean getAutoCommit() throws SQLException
{
// TODO Auto-generated method stub
return con.getAutoCommit();
} public void commit() throws SQLException
{
// TODO Auto-generated method stub
con.commit();
} public void rollback() throws SQLException
{
// TODO Auto-generated method stub
con.rollback();
} public void close() throws SQLException
{
// TODO Auto-generated method stub
con.close();
} public boolean isClosed() throws SQLException
{
// TODO Auto-generated method stub return con.isClosed();
} public DatabaseMetaData getMetaData() throws SQLException
{
// TODO Auto-generated method stub
return con.getMetaData();
} public void setReadOnly(boolean readOnly) throws SQLException
{
// TODO Auto-generated method stub
con.setReadOnly(readOnly);
} public boolean isReadOnly() throws SQLException
{
// TODO Auto-generated method stub
return con.isReadOnly();
} public void setCatalog(String catalog) throws SQLException
{
// TODO Auto-generated method stub
con.setCatalog(catalog);
} public String getCatalog() throws SQLException
{
// TODO Auto-generated method stub
return con.getCatalog();
} public void setTransactionIsolation(int level) throws SQLException
{
// TODO Auto-generated method stub
con.setTransactionIsolation(level);
} public int getTransactionIsolation() throws SQLException
{
// TODO Auto-generated method stub
return con.getTransactionIsolation();
} public SQLWarning getWarnings() throws SQLException
{
// TODO Auto-generated method stub
return con.getWarnings();
} public void clearWarnings() throws SQLException
{
// TODO Auto-generated method stub
con.clearWarnings();
} public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException
{
// TODO Auto-generated method stub
return con.createStatement(resultSetType, resultSetConcurrency);
} public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency)
throws SQLException
{
// TODO Auto-generated method stub
return con.prepareStatement(sql, resultSetType, resultSetConcurrency);
} public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
{
// TODO Auto-generated method stub
return con.prepareCall(sql, resultSetType, resultSetConcurrency);
} public Map<String, Class<?>> getTypeMap() throws SQLException
{
// TODO Auto-generated method stub
return con.getTypeMap();
} public void setTypeMap(Map<String, Class<?>> map) throws SQLException
{
// TODO Auto-generated method stub
con.setTypeMap(map);
} public void setHoldability(int holdability) throws SQLException
{
// TODO Auto-generated method stub
con.setHoldability(holdability);
} public int getHoldability() throws SQLException
{
// TODO Auto-generated method stub
return con.getHoldability();
} public Savepoint setSavepoint() throws SQLException
{
// TODO Auto-generated method stub
return con.setSavepoint();
} public Savepoint setSavepoint(String name) throws SQLException
{
// TODO Auto-generated method stub
return con.setSavepoint(name);
} public void rollback(Savepoint savepoint) throws SQLException
{
// TODO Auto-generated method stub
con.rollback(savepoint);
} public void releaseSavepoint(Savepoint savepoint) throws SQLException
{
// TODO Auto-generated method stub
con.releaseSavepoint(savepoint);
} public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability)
throws SQLException
{
// TODO Auto-generated method stub
return con.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability);
} public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException
{
// TODO Auto-generated method stub
return con.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
} public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException
{
// TODO Auto-generated method stub
return null;
} public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException
{
// TODO Auto-generated method stub
return con.prepareStatement(sql, autoGeneratedKeys);
} public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException
{
// TODO Auto-generated method stub
return con.prepareStatement(sql, columnIndexes);
} public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException
{
// TODO Auto-generated method stub
return con.prepareStatement(sql, columnNames);
} public Clob createClob() throws SQLException
{
// TODO Auto-generated method stub
return con.createClob();
} public Blob createBlob() throws SQLException
{
// TODO Auto-generated method stub
return con.createBlob();
} public NClob createNClob() throws SQLException
{
// TODO Auto-generated method stub
return con.createNClob();
} public SQLXML createSQLXML() throws SQLException
{
// TODO Auto-generated method stub
return con.createSQLXML();
} public boolean isValid(int timeout) throws SQLException
{
// TODO Auto-generated method stub
return con.isValid(timeout);
} public void setClientInfo(String name, String value) throws SQLClientInfoException
{
// TODO Auto-generated method stub
con.setClientInfo(name, value);
} public void setClientInfo(Properties properties) throws SQLClientInfoException
{
// TODO Auto-generated method stub
con.setClientInfo(properties);
} public String getClientInfo(String name) throws SQLException
{
// TODO Auto-generated method stub
return con.getClientInfo(name);
} public Properties getClientInfo() throws SQLException
{
// TODO Auto-generated method stub
return con.getClientInfo();
} public Array createArrayOf(String typeName, Object[] elements) throws SQLException
{
// TODO Auto-generated method stub
return con.createArrayOf(typeName, elements);
} public Struct createStruct(String typeName, Object[] attributes) throws SQLException
{
// TODO Auto-generated method stub
return con.createStruct(typeName, attributes);
} }
3、公共的数据库连接池

/**
* 获取默认数据库连接
* @param uri
* @return
*/
public static DBConn getConnection()
{
DBConn dbConn = new DBConn();
if (!dbConn.createConnection())
{
// 如果创建连接失败
DBSemaphore.unLock();
return null;
} // 连接成功,设置该连接属性
try
{
// 特殊处理连接的AutoCommit是否已经被设置
dbConn.setAutoCommit(true);
dbConn.setInUse();
DBSemaphore.unLock();
return dbConn;
}
catch (Exception ex)
{
ex.printStackTrace();
DBSemaphore.unLock();
return null;
} } /**
* 通过URI地址获取指定数据库连接
* @param uri
* @return
*/
public static DBConn getConnection(String uri)
{
DBConn dbConn = new DBConn(uri);
if (!dbConn.createConnection())
{
// 如果创建连接失败
// DBSemaphore.UnLock();
return null;
}
try
{
// 特殊处理连接的AutoCommit是否已经被设置
dbConn.setAutoCommit(true);
// dbConn.setInUse();
// DBSemaphore.UnLock();
return dbConn;
}
catch (Exception ex)
{
ex.printStackTrace();
// DBSemaphore.UnLock();
return null;
} }

public static void main(String[] args)
{
// 测试连接池 // 1、连接mysql 数据库
Connection conn = DBConnPool.getConnection(); if (conn == null)
{
System.out.println("获取连接失败!");
}
else
{
System.out.println("获取连接成功");
} }



// 连接成功,设置该连接属性
try
{
// 特殊处理连接的AutoCommit是否已经被设置
dbConn.setAutoCommit(true);
dbConn.setInUse();
DBSemaphore.unLock();
return dbConn;
}
catch (Exception ex)
{
ex.printStackTrace();
DBSemaphore.unLock();
return null;
}
新增DBSemaphore类属性及方法如下:
/**
* 数据库同步对象
* @author Damon
*/
public class DBSemaphore
{
private static volatile boolean m_bInUse = false; public DBSemaphore()
{} /**
* 设置"使用标志"。 传入true表示请求“使用标志”,传入false表示释放“使用标志”。
* @param bNewValue boolean
* @return boolean
*/
protected static synchronized boolean setInUseFlag(boolean bNewValue)
{
if (bNewValue == true)
{
// 请求“使用标志”
if (m_bInUse == true)
{
// “使用标志”已经被占用
return false;
}
else
{
m_bInUse = true;
return true;
}
}
else
{
// 释放“使用标志”
m_bInUse = false;
return true;
}
} protected static void lock() throws Exception
{
lock(0);
} protected static void lock(int nSeconds) throws Exception
{
if (nSeconds <= 0)
{
while (!setInUseFlag(true))
{
Thread.sleep(100);
}
}
else
{
while (!setInUseFlag(true) && nSeconds-- > 0)
{
Thread.sleep(100);
} if (nSeconds == 0)
{
throw new Exception("Lock time out");
}
}
} protected static void unLock()
{
setInUseFlag(false);
}
}
到这里,整个配置处理结束了,更多的就需要在实际项目中发挥了~

Java创建连接池连接不同数据库的更多相关文章
- JNDI连接池连接Oracle数据库
今天做了一个评论的小功能,要求用JNDI连接池连接Oracle数据库,以前只是测试了是否连接的上,现在没想到一个JNDI连接池连接Oracle数据库,纠结了好久,原来都是Oracle数据库的问题,这是 ...
- python使用dbutils的PooledDB连接池,操作数据库
1.使用dbutils的PooledDB连接池,操作数据库. 这样就不需要每次执行sql后都关闭数据库连接,频繁的创建连接,消耗时间 2.如果是使用一个连接一直不关闭,多线程下,插入超长字符串到数据库 ...
- spring boot配置druid连接池连接mysql
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
- node 连接MySQL及其分装, 连接池连接
const mysql = require('mysql') const config = require('./../../config/config.default') var connectio ...
- python通过连接池连接redis,操作redis队列
在每次使用redis都进行连接的话会拉低redis的效率,都知道redis是基于内存的数据库,效率贼高,所以每次进行连接比真正使用消耗的资源和时间还多.所以为了节省资源,减少多次连接损耗,连接池的作用 ...
- Java使用数据库连接池连接Oracle数据库
第一步:导入tomcat\lib 下的一个tomcat-dbcp.jar包第二步:在web\META-INF下新建一个context.xml文件,文件内容如下: <?xml version=&q ...
- Spring框架中 配置c3p0连接池 完成对数据库的访问
开发准备: 1.导入jar包: ioc基本jar jdbcTemplate基本jar c3p0基本jar 别忘了mysql数据库驱动jar 原始程序代码:不使用配置文件方式(IOC)生成访问数据库对象 ...
- 关于c3p0连接池连接mysql数据库需要注意的几点
什么是数据库连接池: 用池来管理Connection,这可以重复使用Connection.有了池,所以我们就不用自己来创建Connection,而是通过池来获取Connection对象. 当使用完Co ...
- python - DBUtils 连接池减少oracle数据库的连接数
问题: 接到需求,告知项目的oracle连接次数过多,对系统造成太过大的负担,要求减少oracle数据库的连接次数 分析: 仔细分析代码以后,发现产生问题的原因,在于之前要求提升oracle监控的监控 ...
随机推荐
- {网络编程}和{多线程}应用:基于TCP协议【实现多个客户端发送文件给一个服务器端】--练习
要求: 实现多个客户端发送文件给一个服务器端 提示:多个人创建客户端发送文件,服务端循环接收socket,从socket中获取文件 说明:这里我们只要建立一个服务端就可以了,然后让多台电脑使用客户端给 ...
- 用java实现简单快速的webservice客户端/数据采集器(支持soap1.1和soap1.2标准,支持utf-8编码)
前言: 用了cxf,axis等各种wbeservice实现库,简单试用了一下动态调用的方式,很不满意,完全无法满足业务的需要,所以自己实现了一个webservice采集客户端,方便动态调用外部webs ...
- Spring学习(3)---Spring设值注入和构造注入
(一)设值注入就是指要被注入的类中定义有一个setter()方法,并在参数中定义需要注入的对象.简单的看个例子. 建一个User类: package com.ioc; public class Use ...
- JDK并发包
JDK5之后引进了并发包java.util.concurrent,让并发的开发更加可控,更加简单.所以有必要好好学习下,下面从同步控制.并发容器.线程池三部分来详细了解它. 1. 各种同步控制工具的使 ...
- angular2/angular4 如何通过$http的post方法请求下载二进制的Excel文件
时间有限,废话就不多说了,直接上干货! 下面给大家介绍一下我遇到的一个坑,如果你也遇到了,那恭喜你,你一定能找到答案:angular2/angular4 如何通过$http的post方法请求下载二进制 ...
- Rhythmbox音乐播放器常见问题
一.歌名中文乱码 对于所有用gstreamer做后端的播放器,如Rhythmbox, 设置如下的环境变量后即可正确读取mp3中GBK编码的id3 tag. export GST_ID3_TAG_ENC ...
- Android 的 SDK Manager 无法启动 闪退解决方法
[故障描述] 做 Android 开发就要下载 Android SDK,其中的 SDK Manager.exe 无法启动,一闪而过. 尝试重装 JDK.重新从官网下载 Android SDK.添加环境 ...
- ionic 项目中创建侧边栏的具体流程分4步简单学会
这是在学习ionic时,当时遇到的一些问题,觉得很难,就记笔记下来了,现在觉得如果可以拿来分享,有可能会帮助到遇到同样问题的人 ionic slidemenu 项目流程: cd pretices(自己 ...
- js函数验证方式:验证是否是数字,支持小数,负数
验证 datatype="/^\d+(\.\d+)?$/" validatform验证是否是数字 支持小数点 datatype="d" 貌似支持小数 js函数验 ...
- zend framework 1 安装教程
网上的安装教程总是一笔带过,本人结合已经爬过的坑,为大家展示最简单的安装方式: 博主环境如下: 操作系统:win7 64bit 开发环境:lnmp(phpstudy) 注意: zftest:官方下载的 ...