TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
- 一个学习编写连接池的好例子,有自动调节,输出使用报告等功能。源码请下载,这是如何使用这个连接池的代码:
- import java.sql.*;
- public class SimpleConstructorExample
- {
- // 如果你的数据库不是mysql,请改变这些配置
- static String dbURL = "jdbc:mysql://localhost:3306/store_product";
- static String dbUserName = "";
- static String dbPassword = "";
- static String dbDriver = "org.gjt.mm.mysql.Driver";
- // 展示一个使用构造器的例子
- public static void main(String[] args)
- {
- ConnectionPool pool = new ConnectionPool(); // start a default pool
- try
- {
- pool.setURL( dbURL ); // 数据库 url
- pool.setDriverClassName( dbDriver ); // 驱动程序必须在classpath中!
- pool.setUser( dbUserName ); // 设置用户名
- pool.setPassword( dbPassword ); // 口令
- pool.start(); // 启动连接池
- Connection con = pool.getConnection("Test Program"); // 从池中获取一个连接并标识自己
- useConnection(con); // 使用连接
- pool.returnConnection( con ); // 将连接归还到连接池,以便重用
- System.out.println( pool.getReport() ); // 打印连接池的使用报告
- }
- catch(SQLException e)
- {
- System.out.println( e.getMessage() );
- }
- catch(ClassNotFoundException cnf) // might be thrown by setDriverClassName()
- {
- System.out.println( cnf.getMessage() );
- }
- }
- // 使用连接的简单例子
- public static void useConnection(Connection con) throws SQLException
- {
- System.out.println("仅显示在当前数据库中的表...");
- Statement statmt;
- ResultSet res;
- statmt = con.createStatement();
- String statement = "show tables";
- res = statmt.executeQuery(statement);
- while ( res.next() )
- System.out.println( res.getString(1) );
- res.close();
- statmt.close();
- }
- }
- 下面是作者关于这个连接池的介绍:
- ==========================================================================
- 0. WHAT THIS PROGRAM DOES
- ==========================================================================
- This JDBC Connection Pool is SELF REGULATING. That is, when you create
- the pool, you tell it how big to make itself. If, over time, you need
- more connections than you originally requested, the pool will build new
- ones.
复制代码 These extra connections, if left idle for more than a certain definable
time, will be closed down by the pool to be kind to your database. You can access a report from your pool to find out how many connections
are in it, how long they have been idle, which ones are being used, and
what program is using the used connections. ==========================================================================
1. ABOUT THE AUTHOR
========================================================================== Jeff Patterson - from Portland, Oregon. Senior type programmer guy. On the web at : http://www.webdoyen.com
Email me at : jeff@webdoyen.com
源码下载:http://file.javaxxz.com/2014/10/1/223146156.zip |
|