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监控的监控 ...
随机推荐
- java基础(三章)
java基础(三章) 一.基本if结构 1.流程图 l 输入输出 l 判断和分支 l 流程线 1.1 简单的if条件判断 if(表达式){ //表 ...
- 允许mysql用户从远程登录
1.修改/etc/mysql/my.cnf,将下面的行注释掉bind=127.0.0.1注释#bind=127.0.0.1 2.修改用户权限,允许从任何主机登录mysql>use mysql;m ...
- PHP中常量和变量的区别
1.常量只能赋一次值: 以下是申请常量的两种方法: const THE_VALUE="one"; define("THE_VALUE","one&qu ...
- windows端口占用处理工具
一.描述 笔者在最近使用tomcat时,老是会遇到这种端口占用的问题,便写了这个小的exe,用于解决windows下的端口占用问题. 好吧,其实是我实在记不住CMD下的那几行命令.这玩意的实现比较简单 ...
- 增强学习 | AlphaGo背后的秘密
"敢于尝试,才有突破" 2017年5月27日,当今世界排名第一的中国棋手柯洁与AlphaGo 2.0的三局对战落败.该事件标志着最新的人工智能技术在围棋竞技领域超越了人类智能,借此 ...
- 类型转换之 PropertyEditorSupport类
这个类可以用于自定义的类型转换, 子类继承这个类之后可以重写子类的方法 ,其中比较重要的是setAsText和setValue方法,setAsText 子自己的方式处理转换,setValue将转换的结 ...
- 针对Oracle数据库表中的数据的常见操作
1.查询表中所有数据 select * from 表名; 例:select * from stu; 2.查询的同时修改表中数据 select * from 表名 for update; 例:sele ...
- php打包文件为ZIP包后下载到本地
这是一个工作中需要打包下载当前产品的所有图片到本地,文件格式为ZIP压缩包,打包下载文件跟图片一样,本程序细节为实际情况,使用需按照自己实际情况书写:<?php/**************** ...
- html的基本标记符号
文本标记:<h1><h2><h3><h4><h5><h6>: 段落标记:<p>: 空格: : 换行: ...
- Java虚拟机-----------Java内存区域与内存溢出异常
Java内存区域划分 Java虚拟机运行时的数据区大致可划分为五部分:方法区,堆(两部分组成Java堆内存),虚拟机栈,本地方法栈(Java栈内存),程序计数器. 1.程序计数器 程序计数器占较小的内 ...