首页 技术 正文
技术 2022年11月15日
0 收藏 594 点赞 2,618 浏览 13022 个字

在一个应用里面,可能涉及到连接多个不同数据库进行操作,而每次连接写不同的实现会很麻烦。前面已经会了用JDBC连接数据库,那么利用反射和工厂模式,可以实现连接不同的数据库,这样处理起来将会很方便。同时建造数据库连接池,处理多个业务数据处理。  Java创建连接池连接不同数据库

那么具体怎么实现呢,下面一起来看一下:整体结构如下:

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

Java创建连接池连接不同数据库第一步,先处理连接不同数据库1、首先,将数据库配置信息创建一个公用类:JdbcUrl.java主数据库可以用默认的构造方法,如果是连接其他库,则通过传递参数的方式来处理。数据库参数有如下几个: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接口的方法,同时连接数据库。

参数有已实现的JdbrUrl类,主要新增方法为:createConnection()根据DBType来对不同数据库进行处理:加载对应的数据库,然后获取数据库连接。Java创建连接池连接不同数据库

 **
* 数据库连接类,连接数据库
* @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、公共的数据库连接池

数据库配置和数据库连接已经搞定,那么可以建一个数据库连接池来进行数据库的连接及处理。Java创建连接池连接不同数据库主要有2个方法,连接默认数据库和连接指定的数据库。

 /**
* 获取默认数据库连接
* @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;
} }

Java创建连接池连接不同数据库可以写一个测试方式,这也数据库连接就完成了,通过传入不同的参数就可以获取到不同数据库的连接了。

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

第二步,构建数据库连接池前面已经实现连接不同数据库,那么怎么处理为连接池呢?数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个;释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据库连接遗漏。这项技术能明显提高对数据库操作的性能。下面我们就来实现数据库连接池的功能:

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

Java创建连接池连接不同数据库数据库连接池的实现思想主要有如下几个方面:1、可定义最大和最小的连接数:如果请求小于最小连接数,则直接分配连接,达到最大连接数则新请求等待;2、用户在连接数据库时,不用新建连接,而是直接从连接池中获取连接,使用完毕后也不用关闭,而是释放给连接池,供下一个用户使用;下面来进行实现:其实就是实现了一个数据连接数的判断,最大连接数进行限制,实际的数据库连接池需结合对应的数据库连接池组件(比如 WebSphere等中间件),在判断是否有连接在使用的时候,会涉及到并发,这里需要用到volatile关键字。 其中,增加了DBsemaphor类,用以处理连接的使用和释放。在原有DBConn基础上,加上是否已使用方法,在获取连接成功时调用,具体代码如下:Java创建连接池连接不同数据库

 // 连接成功,设置该连接属性
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创建连接池连接不同数据库 

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,084
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,559
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,408
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,181
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,818
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,901