站内搜索: 请输入搜索关键词

当前页面: 开发资料首页Java 专题一个学习编写连接池的好例子

一个学习编写连接池的好例子

摘要: 一个学习编写连接池的好例子

</td> </tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td height="86" align="left" valign="top"> </td> </tr> </table>
一个学习编写连接池的好例子,有自动调节,输出使用报告等功能。源码请下载,这是如何使用这个连接池的代码:
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

</td> </tr> <tr>


↑返回目录
前一篇: Lucene索引查询分页实例
后一篇: 用Tomcat建立基于主机名的虚拟主机