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监控的监控 ...
随机推荐
- Selenium基础知识
本人博客文章网址:https://www.peretang.com/basic-knowledge-of-selenium/ 什么是Selenium Selenium是一个自动化测试工具 是一组不同的 ...
- 【数据库】Mean web开发 02-Windows下Mongodb安装配置及常用客户端管理工具
简介 Mean是JavaScript的全栈开发框架.更多介绍 用MongoDB实现持久数据的存储是Mean Web全栈开发中的一部分. MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非 ...
- HashMap如何工作 - Java
大多数人应该会同意HashMap是现在面试最喜欢问的主题之一.我和同事常常进行讨论,并很有帮助.现在,我继续和大家讨论. 我假设你对HashMap的内部工作原理感兴趣,并且你已经知道了基本的HashM ...
- JavaScript面向对象之Windows对象
JavaScript之Window对象 首先我们先了解一个概念:事件. 事件,就是把一段代码设置好,满足条件时触发.或者说,事件是可以被 JavaScript 侦测到的行为. 网页中每个元素都可以触发 ...
- Android 创建虚拟机时“提示no system images installed for this target”
经上网查证,发现原因在于CPU/ABI选项无法选择,并显示“No system images installed for this target”,也就是没有适合的系统镜像,通过与安装好了的ADT-b ...
- JS键盘事件对象之keyCode、charCode、which属性对比
先说一些有关键盘事件的事项:用js实现键盘记录,要关注浏览器的三种按键事件类型,即keydown,keypress和keyup,它们分别对应onkeydown. onkeypress和onkeyup这 ...
- CSS设置一行文字,超出部分自动隐藏
.textone { overflow: hidden; text-overflow: ellipsis; display: -webkit-box; line-height: 25px; max-h ...
- ionic 的缓存 和局部刷新
最近两天在做项目时,发现ionic的缓存功能非常方便好用,提高了再低端手机特别是android比较低版本上的流畅性!可是,后来发现,整体的缓存整个页面并不是一个一劳永逸的办法,结合局部刷新功能,感觉就 ...
- .Net Mvc Automated Migration 数据迁移
1.打开程序包管理器控制台 PM> enable-migrations –EnableAutomaticMigration:$true 2.项目工程文件中会生成Migrations文件夹 3.找 ...
- 前端程序员的蜕变——JS的 event 对象属性、使用实例、兼容性处理(极大提高代码效率、减少代码量)
下面讨论一下 js 中的 Event 对象,主要从以下三个方面详细的描述(点击标题可跳转到对应部分): 1.什么是event 2.怎么用event,用他该注意什么,几个简单实际应用 3.event在不 ...