Java 访问数据库的线程池实现

DBConnection.java
 

package com.game.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;

public class DBConnection {

	private static int maxConnectNum = 20;

	private java.sql.Connection conn[] = new Connection[maxConnectNum];

	private static ArrayList<Connection> connectPool = new ArrayList<Connection>();

	private static int flag = 0;

	public DBConnection() {
		if (flag == 0) {
			init();
		}
	}

	private Connection getConnectionFromDatabase() {
		Connection trueConn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			String url = "jdbc:mysql://localhost:3306/rpgdb?user=root&password=&characterEncoding=UTF8";
			trueConn = DriverManager.getConnection(url);
		} catch (Exception ex) {
			System.out.println("数据连接出错了:" + ex.toString());
		}
		return trueConn;
	}

	// 这里建立所有的连接;
	private void init() {
		for (int i = 0; i < maxConnectNum; i++) {
			conn[i] = getConnectionFromDatabase();
			connectPool.add(i, conn[i]);
		}
		flag = 1;
	}

	// 从连接池中取得一个可用的连接
	public Connection getConnection() {
		Connection conn = null;
		if (connectPool.size() == 0) {
			try {
				java.lang.Thread.sleep(1000);
				getConnection();
			} catch (InterruptedException ex) {
				System.out.println("连接全部用光,这里sleep出错了.");
			}
		} else {
			conn = (Connection) connectPool.remove(0);
		}

		return conn;
	}

	// 提供给外部程序调用,不用的连接放回连接池当中...
	public boolean release(Connection conn) {
		return connectPool.add(conn);
	}
}

MysqlHelper.java

package com.game.database;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import com.mysql.jdbc.Statement;
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;

/**
 * <strong>mysql数据库操作帮助类</strong>
 * <p>
 * 包装了mysql常用的操作方法。类似于SqlHelper在java中的实现。
 * </p>
 * 
 * @author birdshover
 */
public abstract class MysqlHelper {
    private static Boolean locker = false;
    
    private static DBConnection dbConn = new DBConnection();
    
    /**
     * 返回数据库连接对象,连接失败则返回null
     * 
     * @return Connection
     */
    private static Connection getConnection() {
        try {
        	return dbConn.getConnection();
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 无结果查询,适用于更新和插入
     * 
     * @param SQL语句
     * @param 语句带的参数
     * @return 操作影响行数
     * @throws SQLException
     * 
     * @example Object[] parms = new Object[2];<br/> parms[0] = "标题"; <br/>
     *          parms[1] = "内容";<br/> int val = mysqlhelper.ExecuteNoneQuery(
     *          "insert into Documents(Title,Content) values (?,?)", parms);
     */
    public static int ExecuteNoneQuery(String cmdtext, Object[] parms)
            throws SQLException {
        PreparedStatement pstmt = null;
        Connection conn = null;
        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(cmdtext);
            prepareCommand(pstmt, parms);
            return pstmt.executeUpdate();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        } finally {
            if (pstmt != null){
                pstmt.clearParameters();
                pstmt.close();
            }
            dbConn.release(conn);
        }
        return 0;
    }
    /**
     * 插入 返回 insert id
     * 
     * @param SQL语句
     * @param 语句带的参数
     * @return 操作影响行数
     * @throws SQLException
     * 
     * @example Object[] parms = new Object[2];<br/> parms[0] = "标题"; <br/>
     *          parms[1] = "内容";<br/> int val = mysqlhelper.ExecuteInsert(
     *          "insert into Documents(Title,Content) values (?,?)", parms);
     */
    public static int ExecuteInsert(String cmdtext, Object[] parms)
            throws SQLException {
        PreparedStatement pstmt = null;
        Connection conn = null;
        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(cmdtext,Statement.RETURN_GENERATED_KEYS);
            prepareCommand(pstmt, parms);
            pstmt.executeUpdate();
            ResultSet rs = pstmt.getGeneratedKeys();
            if(rs.next()){
            	return rs.getInt(1);
            }
            else
            	return 0;
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        } finally {
            if (pstmt != null){
                pstmt.clearParameters();
                pstmt.close();
            }
            dbConn.release(conn);
            
        }
        return 0;
    }
    /**
     * 返回查询结果集
     * 
     * @param SQL语句
     * @param 附带参数
     * @return 返回结果,用ArrayList包装Object数组
     * @throws SQLException
     * 
     * @example ArrayList list =
     *          mysqlhelper.ExecuteReader("Select * from Documents",null); <br/>
     *          for(int i = 0;i<list.size();i++) { <br/>   Object[]
     *          obs = (Object[])list.get(i); <br/>   for(int j =
     *          0;j<obs.length;j++) { <br/>
     *              out.print(obs[j].toString()); <br/>
     *            } <br/>   out.print("<br/>"); <br/>
     *          } <br/>
     * 
     */
    public static ArrayList ExecuteReader(String cmdtext, Object[] parms)
            throws SQLException {
        PreparedStatement pstmt = null;
        Connection conn = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(cmdtext);

            prepareCommand(pstmt, parms);
            rs = pstmt.executeQuery();

            ArrayList al = new ArrayList();
            ResultSetMetaData rsmd = rs.getMetaData();
            int column = rsmd.getColumnCount();

            while (rs.next()) {
                Object[] ob = new Object[column];
                for (int i = 1; i <= column; i++) {
                    ob[i - 1] = rs.getObject(i);
                }
                al.add(ob);
            }
            return al;

        } catch (Exception ex) {
        }
        finally{
            if (rs != null)
                rs.close();
            if (pstmt != null)
                pstmt.close();
            dbConn.release(conn);
        }
        return null;
    }
    
    public static HashMap<String, Object> ExecuteRow(String cmdtext, Object[] params)
    throws SQLException
    {
    	 PreparedStatement pstmt = null;
         Connection conn = null;
         ResultSet rs = null;
         try {
             conn = getConnection();

             pstmt = conn.prepareStatement(cmdtext);
             prepareCommand(pstmt, params);

             rs = pstmt.executeQuery();
             ResultSetMetaData rsmd = rs.getMetaData();
             int column = rsmd.getColumnCount();
             if (rs.next()) {
            	 HashMap<String, Object> ob = new HashMap<String, Object>();
                 for (int i = 1; i <= column; i++) {
                     ob.put(rsmd.getColumnName(i), rs.getObject(i));
                 }
            	 return ob;
             } else {
                 return null;
             }
         } catch (Exception e) {
             System.out.println(e.getMessage());
         } finally {
             if (rs != null)
                 rs.close();
             if (pstmt != null)
                 pstmt.close();
             dbConn.release(conn);
         }
         return null;
    }

    /**
     * 返回第1行第1列数据,一般用来查询count值
     * 
     * @param SQL语句
     * @param 带参数
     * @return 值
     * @throws SQLException
     */
    public static Object ExecuteScalar(String cmdtext, Object[] parms)
            throws SQLException {
        PreparedStatement pstmt = null;
        Connection conn = null;
        ResultSet rs = null;
        try {
            conn = getConnection();

            pstmt = conn.prepareStatement(cmdtext);
            prepareCommand(pstmt, parms);

            rs = pstmt.executeQuery();
            if (rs.next()) {
                return rs.getObject(1);
            } else {
                return null;
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            if (rs != null)
                rs.close();
            if (pstmt != null)
                pstmt.close();
            dbConn.release(conn);
        }
        return null;
    }

    private static void prepareCommand(PreparedStatement pstmt, Object[] parms)
            throws SQLException, IOException {
        if (parms != null && parms.length > 0) {
            for (int i = 1; i < parms.length + 1; i++) {
                Object item = parms[i - 1];
                String typeName = item.getClass().getSimpleName();
                if (typeName.equals("String")) { 
                    pstmt.setString(i, item.toString());
                } else if (typeName.equals("Integer")) {
                    pstmt.setInt(i, Integer.parseInt(item.toString()));
                } else if (typeName.equals("Date")) {
                    pstmt.setDate(i, Date.valueOf(item.toString()));
                } else if (typeName.equals("byte[]")) {
                	InputStream is = new ByteInputStream((byte[])item,((byte[])item).length);
                	pstmt.setBinaryStream(i, is, is.available());
                } else {
                    pstmt.setObject(i, item);
                }
            }
        }
    }
}


这两个类结合之后,使用方法就是直接可以调用

Object[] params = new Object[1];
params[0] = 1000;
Object name = MysqlHelper.ExecuteScalar("select name from sys_user where id = ?", params);
System.out.println(name);


需要注意的是,MysqlHelper的每次调用里面不应该关闭连接,不然连接池的作用就没有了。
说明:以上两个类都是网上down下来,自己根据使用习惯进行修改,感谢他们的代码分享。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值