因为项目后台中需要管理各个游戏数据库里的游戏参数配置,所以需要动态的根据游戏部署情况来调整数据库链接源。

  一共3个类:


第一个dbcp工具类:

package com.jdbcUtil;


import java.sql.Connection;

import java.sql.SQLException;

import java.util.List;

import java.util.concurrent.ConcurrentHashMap;


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;

    }


}