论坛首页 Java企业应用论坛

池连代码

浏览 1520 次
该帖已经被评为隐藏帖
作者 正文
   发表时间:2007-08-21  
/**
*Source File Name:   ConnectionPool.java
*
*连接池类
*
*经过测式:可以作为(池连)连接数据库之用
*
*
*登陆MySQL时;mysql -uroot -p --default-character-set=gbk;
*
*/
package utilcom;

import java.sql.*;
import java.util.Date;
import java.util.Vector;

public class ConnectionPool {

    private String jdbcDriver;

    private String host;

    private String tableName;

    private String userName;

    private String password;

    private static int maxConnections = 5;

    private static int minConnections =1;

    private Vector conns;
   
    //计录连接数
    private int connections;

    public ConnectionPool(String driver, String host, String table,
            String user, String pw) {
        jdbcDriver = "com.mysql.jdbc.Driver";
        this.host = "localhost";
        tableName = null;
        userName = null;
        password = null;
        connections = 0;
        if (driver != null)
            jdbcDriver = driver;
        if (host != null)
            this.host = host;
        if (table != null)
            tableName = table;
        if (user != null)
            userName = user;
        if (pw != null)
            password = pw;
        conns = new Vector();
        try {
            init();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void setConnectionAmounts(int min, int max) {
        if (min > -1)
            minConnections = min;
        if (max > min)
            maxConnections = max;
        try {
            closeAll();
            init();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public Connection openConnection() {
        try {
            return get(0);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void closeConnection(Connection conn) {
        ret(conn);
    }

    public int getConnectionAmount() {
        return getConnAmount();
    }
   
    /**
     *
     * @throws SQLException
     */
    protected void init() throws SQLException {
        connections = minConnections;
        try {
            //加载数据库驱动
            Class.forName(jdbcDriver).newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
            throw new SQLException(e.getMessage());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            throw new SQLException(e.getMessage());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new SQLException(e.getMessage());
        }
        for (int i = 0; i < minConnections; i++){
            conns.add(i, newConnection());          
        }
    }

    private void closeAll() throws SQLException {
        for (int i = 0; i < conns.size(); i++) {
            Connection conn = (Connection) conns.get(i);
            conn.close();
        }

    }

    private Connection get(int step) throws SQLException {
       
        //conns.size() > 0 ==true 说明向量中有连接
        if (conns.size() > 0) {
            Connection conn = (Connection) conns.remove(0);
            if (conn == null || conn.isClosed())
                conn = newConnection();
            return conn;
        }
        if (step > 50)
            return null;
        //如果在用的连接数大于等于maxConnections,等待后递归,
        //反之新建连接connections++
        if (connections >= maxConnections) {
            try {
                Thread.sleep(100L);
            } catch (InterruptedException interruptedexception) {
            }
            return get(step++);
        } else {
            connections++;
            return newConnection();
        }
    }

    private void ret(Connection conn) {
        try {
            if (conn == null)
                conn = newConnection();
            conns.add(conn);
        } catch (SQLException e) {
            connections--;
        }
    }

    private Connection newConnection() throws SQLException {
        System.out.println("Create connection to DB--");
        return DriverManager.getConnection("jdbc:mysql://" + host + "/"
                + tableName + "?user=" + userName + "&password=" + password);
    }

    public int getConnAmount() {
        return connections;
       
    }
   
    protected void finalize() {
        try {
           
            closeAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /**
     * 测式用主涵数
     */
    public static void main(String[] arge) {
        long time=new Date().getTime();
      //  PoolMan pm = new PoolMan();
       ConnectionPool cp=new ConnectionPool("com.mysql.jdbc.Driver","localhost:3306","test","root","");
        try {
           // for(int i=0;i<5000;i++){
                Vector v=new Vector(100,10);
                Connection cn = cp.openConnection();
                Statement stmt = cn.createStatement();
               
                //设置字符编码格式为:GBK
                stmt.execute("set names gbk");
                ResultSet rs = stmt.executeQuery("select * from test");
                while (rs.next()) {
                   // System.out.println(rs.getString("msisdn") + rs.getString("nickname"));
                   
                    System.out.println(rs.getString("name"));
                    v.add(rs.getString("name"));
                }
               
                //cp.closeConnection(cn);
                rs.close();
                for(int i=0;i<v.size();i++){
                    String temp =(String)v.get(i);
                   // temp=temp.replaceAll("\n","");
                    //将记录中的一个“\”替换成“\\”插入数据库中后显示应然是“\”
                    temp=temp.replaceAll("\\\\","\\\\\\\\");
                    String sql="insert into test (name)values('"+temp+"')";
                   
                    System.out.println(sql);
                   // stmt.executeUpdate(sql);  
                }
            //    System.out.println(i);
        //   }
            System.out.println(new Date().getTime()-time);
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            try {
                System.out.println("close connection---");
                cp.closeAll();   
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics