由於項目後臺中須要管理各個遊戲數據庫裏的遊戲參數配置,因此須要動態的根據遊戲部署狀況來調整數據庫連接源。java
一共3個類:mysql
第一個dbcp工具類:sql
package com.jdbcUtil;數據庫
import java.sql.Connection;apache
import java.sql.SQLException;json
import java.util.List;緩存
import java.util.concurrent.ConcurrentHashMap;ide
import javax.sql.DataSource;工具
import org.apache.commons.dbcp.BasicDataSource;測試
import com.jdbcUtil.JdbcConfig;
/**
* 數據源鏈接池dbcp 工廠類
*
* @author panguixiang
* @version $Id: DataSourceFactory.java, v 0.1 2016年1月15日 下午12:14:50 Exp $
*/
public class DataSourceFactory {
private static ConcurrentHashMap<String, DataSource> map = new ConcurrentHashMap<String, DataSource>();
/**
* 根據jdbc參數得到數據源鏈接池dbcp,並放入ConcurrentHashMap
*
* @param param
*/
public static void initDataSource(List<JdbcConfig> mapList) {
BasicDataSource ds = null;
for (JdbcConfig config : mapList) {
ds = new BasicDataSource();
ds.setDriverClassName(config.getDriverClass().trim());
ds.setUsername(config.getUsername().trim());
ds.setPassword(config.getPassword().trim());
ds.setUrl(config.getConnectUrl().trim());
ds.setInitialSize(config.getInitialSize());
ds.setMaxActive(config.getMaxActive());
ds.setMaxIdle(config.getMaxIdle());
ds.setMaxWait(config.getMaxWait());
ds.setValidationQuery("select 1");//檢查連接是否有效
DataSource DS = ds;
map.put(config.getDataSourceKey().trim(), DS);
}
}
/**
* 插入數據源鏈接池到緩存
*
* @param config
*/
public static void saveDataSource(JdbcConfig config) {
if (config != null) {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(config.getDriverClass().trim());
ds.setUsername(config.getUsername().trim());
ds.setPassword(config.getPassword().trim());
ds.setUrl(config.getConnectUrl().trim());
ds.setInitialSize(config.getInitialSize());
ds.setMaxActive(config.getMaxActive());
ds.setMaxIdle(config.getMaxIdle());
ds.setMaxWait(config.getMaxWait());
ds.setValidationQuery("select 1");//檢查連接是否有效
DataSource DS = ds;
map.put(config.getDataSourceKey().trim(), DS);
}
}
/**
* 從緩存裏刪除指定的數據源鏈接池
*
* @param sourceKey
* @throws Exception
*/
public static void removeDataSource(String sourceKey) throws Exception {
DataSource DS = map.get(sourceKey.trim());
shutdownDataSource(DS);//先關閉
map.remove(sourceKey.trim());
}
/**
* 修改數據源鏈接池到緩存
*
* @param config
*/
public static void updateDataSource(JdbcConfig config) throws Exception {
if (config != null) {
removeDataSource(config.getDataSourceKey());//先將原有數據源鏈接池從緩存中刪除
/**
* 從新新增
*/
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(config.getDriverClass().trim());
ds.setUsername(config.getUsername().trim());
ds.setPassword(config.getPassword().trim());
ds.setUrl(config.getConnectUrl().trim());
ds.setInitialSize(config.getInitialSize());
ds.setMaxActive(config.getMaxActive());
ds.setMaxIdle(config.getMaxIdle());
ds.setMaxWait(config.getMaxWait());
ds.setValidationQuery("select 1");//檢查連接是否有效
DataSource DS = ds;
map.put(config.getDataSourceKey().trim(), DS);
}
}
/**
* 得到dbcp鏈接池
*
* @param sourceKey
* @return
*/
public static DataSource getDataSource(String sourceKey) {
DataSource DS = map.get(sourceKey.trim());
return DS;
}
/**
* 得到一個數據庫鏈接 ,從dbcp鏈接池
*
* @param source
* @return
*/
public static Connection getConnection(DataSource source) {
Connection con = null;
if (source != null) {
try {
con = source.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
//回收數據庫鏈接時,直接使用con.close()便可
return con;
}
/**
*
*
* @param source
* @throws SQLException
*/
protected static void shutdownDataSource(DataSource source) throws SQLException {
if (source != null) {
BasicDataSource bds = (BasicDataSource) source;
bds.close();//這個close實際上是回收,並非真正的關閉了connction連接
}
}
}
第二個jdbc工具類:
package com.jdbcUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JdbcUtils {
/**
* 新增,修改,刪除 數據
*
* @param sourceKey
* @param sql
* @param params
* @return
* @throws SQLException
*/
public static int updateByPreparedStatement(String sourceKey, String sql, List<Object> params) {
DataSource source = DataSourceFactory.getDataSource(sourceKey);//經過數據鏈接池標識sourceKey,從緩存裏得到一個數據鏈接池
Connection connection = DataSourceFactory.getConnection(source);//從數據鏈接池裏得到數據庫鏈接
int result = -1;// 表示當用戶執行添加刪除和修改的時候所影響數據庫的行數
PreparedStatement pstmt = null;
try {
pstmt = connection.prepareStatement(sql);
int index = 1;
// 填充sql語句中的佔位符
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
result = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
releaseConn(null, pstmt, connection);//用完後,執行此操做回收鏈接
}
return result;
}
/**
* 查詢單條記錄
*
* @param sourceKey
* @param sql
* @param params
* @return
* @throws SQLException
*/
public static JSONObject findSimpleResult(String sourceKey, String sql, List<Object> params) {
DataSource source = DataSourceFactory.getDataSource(sourceKey);
Connection connection = DataSourceFactory.getConnection(source);
JSONObject json = null;
int index = 1;
PreparedStatement pstmt = null;
ResultSet resultSet = null;
try {
pstmt = connection.prepareStatement(sql);
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
resultSet = pstmt.executeQuery();// 返回查詢結果
// 獲取此 ResultSet 對象的列的編號、類型和屬性。
ResultSetMetaData metaData = resultSet.getMetaData();
int col_len = metaData.getColumnCount();// 獲取列的長度
String cols_name;
Object cols_value;
if (resultSet.next())// 得到列的名稱
{
json = new JSONObject();
for (int i = 0; i < col_len; i++) {
cols_name = metaData.getColumnLabel(i + 1);
cols_value = resultSet.getObject(cols_name);
if (cols_value == null)// 列的值沒有時,設置列值爲「」
{
cols_value = "";
}
json.put(cols_name, cols_value);
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
releaseConn(resultSet, pstmt, connection);
}
return json;
}
/**
* 查詢記錄列表
*
* @param sourceKey
* @param sql
* @param params
* @return
* @throws SQLException
*/
public static JSONArray findMoreResult(String sourceKey, String sql, List<Object> params) {
DataSource source = DataSourceFactory.getDataSource(sourceKey);
Connection connection = DataSourceFactory.getConnection(source);
JSONArray list = new JSONArray();
int index = 1;
PreparedStatement pstmt = null;
ResultSet resultSet = null;
try {
pstmt = connection.prepareStatement(sql);
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
resultSet = pstmt.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
int cols_len = metaData.getColumnCount();
String cols_name;
Object cols_value;
while (resultSet.next()) {
JSONObject json = new JSONObject();
for (int i = 0; i < cols_len; i++) {
cols_name = metaData.getColumnLabel(i + 1);
cols_value = resultSet.getObject(cols_name);
if (cols_value == null) {
cols_value = "";
}
json.put(cols_name, cols_value);
}
list.add(json);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
releaseConn(resultSet, pstmt, connection);
}
return list;
}
/**
* 經過count(1)獲取記錄總數
* 寫法: select count(1) from tabl_name;
* select count(1) from tabl_nameA a left join tabl_nameB b on a.rowid=b.rowid;
* @param sourceKey
* @param sql
* @param params
* @return
* @throws SQLException
*/
public static long getCount(String sourceKey, String sql, List<Object> params) {
DataSource source = DataSourceFactory.getDataSource(sourceKey);
Connection connection = DataSourceFactory.getConnection(source);
PreparedStatement pstmt = null;
ResultSet resultSet = null;
long count = 0L;
try {
pstmt = connection.prepareStatement(sql);
int index = 1;
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
resultSet = pstmt.executeQuery();
if (resultSet.next()) {
count = resultSet.getLong(1);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
releaseConn(resultSet, pstmt, connection);
}
return count;
}
/**
* 回收連接
*
* @param resultSet
* @param pstmt
* @param source
*/
public static void releaseConn(ResultSet resultSet, PreparedStatement pstmt,
Connection connection) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 測試
*
* @param args
*/
public static void main(String[] args) {
List<Object> params = new ArrayList<Object>();
String sql = " UPDATE server_parameters_stock_control SET name=? where id=?";
params.add("testName");
params.add(1);
String dbSourceKey = "test_db";
/**
* 調用jdbc工具類執行sql
*/
JdbcUtils.updateByPreparedStatement(dbSourceKey, sql.toString(), params);
}
}
第三個 數據庫表配置jdbc連接參數的model:
package com.jdbcUtil;
/**
* jdbc初始化連接數據庫參數
*
* @author panguixiang
* @version $Id: JdbcParam.java, v 0.1 2016年1月15日 下午12:56:31 Exp $
*/
public class JdbcConfig {
/** */
private static final long serialVersionUID = -1944977364797076255L;
private Integer id;
private String connectUrl; //數據庫連接url
private String username; //數據庫登陸用戶名
private String password; //登陸密碼
private String driverClass = "com.mysql.jdbc.Driver";
private int initialSize = 10;
private int maxActive = 20;
private int maxIdle = 5;
private int maxWait = 5000;
private String createdTs;
private String dataSourceKey; //數據鏈接池 key 數據源標識 ,任意字符串可是需惟一,
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getConnectUrl() {
return connectUrl;
}
public void setConnectUrl(String connectUrl) {
this.connectUrl = connectUrl;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriverClass() {
return driverClass;
}
public void setDriverClass(String driverClass) {
this.driverClass = driverClass;
}
public int getInitialSize() {
return initialSize;
}
public void setInitialSize(int initialSize) {
this.initialSize = initialSize;
}
public int getMaxActive() {
return maxActive;
}
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
public int getMaxIdle() {
return maxIdle;
}
public void setMaxIdle(int maxIdle) {
this.maxIdle = maxIdle;
}
public int getMaxWait() {
return maxWait;
}
public void setMaxWait(int maxWait) {
this.maxWait = maxWait;
}
public String getCreatedTs() {
return createdTs;
}
public void setCreatedTs(String createdTs) {
this.createdTs = createdTs;
}
public String getDataSourceKey() {
return dataSourceKey;
}
public void setDataSourceKey(String dataSourceKey) {
this.dataSourceKey = dataSourceKey;
}
}