免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1619 | 回复: 0
打印 上一主题 下一主题

javaBean+tomcat+MySql连接池三步曲(原创) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-12-19 14:26 |只看该作者 |倒序浏览
最近学习jsp,现将心得给大家一起分享,水平有限,高手勿见笑.
如题,开始吧
第一步: 创建数据库并在tomcat下配置链接池
1.创建数据库
在mysql下创建名为testdb的数据库,在testdb下创建数据表test_table.字段id,name
2.tomcat配置
我们在C:\Program Files\Tomcat 5.5.7\conf\content.xml文件中添加如下数据库链接池配置,如果没有就新建一个content.xml,注意tomcat版本要5.5以上,5.5以下不支持content.xml。

  1. <Context>
  2.         <Resource name="jdbc/testdb"
  3.         auth="Container"
  4.         type="javax.sql.DataSource"
  5.         driverClassName="com.mysql.jdbc.Driver"
  6.         url="jdbc:mysql://localhost/mytestdb"
  7.         username="root"
  8.         password="******"
  9.         maxActive="100"
  10.         maxIdle="30"
  11.         maxWait="10000"
  12.         ></Resource>       
  13. </Context>
复制代码


第二步:编写javaBean读取tomcat下的content.xml
javaBean 文件DataBase.java代码

  1. package withouttears.bean;

  2. import java.util.HashMap;
  3. import java.sql.*;
  4. //JNDI有两个核心接口Context和DirContext,
  5. //Context中包含了基本的名字操作,而DirContext则将这些操作扩展到目录服务。
  6. import javax.naming.Context;
  7. import javax.naming.InitialContext;
  8. //数据库资源的连接工厂是javax.sql.DataSource对象,
  9. //它可以创建java.sql.Connection数据库连接对象。
  10. import javax.sql.DataSource;
  11. //目前您可以从Java开发者连接(http://developer.java.sun.com/developer/earlyAccess/crs)
  12. //下载CachedRowSet的实现。下载并解压缩安装文件后,将"rowset.jar"文件放到您的类目录下。
  13. //CachedRowSet在sun.jdbc.rowset包中。
  14. import sun.jdbc.rowset.CachedRowSet;

  15. /**
  16. * <b>类</b>: DataBase<br>
  17. * <b>版本</b>: 1.0.0<br>
  18. * <b>作者</b>: wiThouTTears<br>
  19. * <b>时间</b>: 2006-12-18<br>
  20. * <b>QQ</b>: 314765755<br>
  21. * <b>Email</b>: wiThouT--Tears@163.com<br>
  22. * <b>Blog</b>: http://wiThouTTears.cublog.cn<br>
  23. * <b>功能</b>: 用连接池连接MySql数据库及相关操作<br>
  24. * */
  25. public class Database {
  26.     /**
  27.      * 数据库JNDI名称,默认:jdbc/testdb
  28.      * */
  29.     private String jndiName="jdbc/testdb";
  30.     /**
  31.      * 建立连接池
  32.      * @param null
  33.      * @return  DataSource
  34.      * */
  35.     private DataSource localhost(){
  36.         DataSource ds=null;
  37.         //在HashMap中通过get()来获取value,通过put()来插入value,
  38.         //ContainsKey()则用来检验对象是否已经存在
  39.         HashMap<Object,Object>  cachedDs=new HashMap<Object,Object> ();
  40.         if(cachedDs.containsKey("ds"))//取出空闲状态的数据库连接
  41.             {
  42.                 /* 在DataSource中事先建立了多个数据库连接,
  43.                  * 这些数据库连接保存在连接池(Connect Pool)中。
  44.                  * Java程序访问数据库时,只需要从连接池中取出空闲状态的数据库连接;
  45.                  * 当程序访问数据库结束,再将数据库连接放回连接池。
  46.                  * */
  47.                 ds = (DataSource)cachedDs.get("ds");
  48.             }
  49.         else
  50.             try
  51.             {
  52.                     /*在javax.naming包中提供了Context接口,
  53.                      * 该接口提供了将对象和名字绑定,以及通过名字检索对象的方法。
  54.                      * */
  55.                 Context initCtx = new InitialContext();
  56.                 //lookup(String name):返回与指定的名字绑定的对象,获得数据库连接工厂
  57.                 ds = (DataSource)initCtx.lookup("java:comp/env/"+getjndiName());
  58.                 cachedDs.put("ds", ds);
  59.             }
  60.             catch(Exception e)
  61.             {
  62.                 e.printStackTrace();
  63.             }
  64.                 return ds;
  65.         }
  66.     /**
  67.      * 库的连接
  68.      * @param null
  69.      * @return  Connection
  70.      * */
  71.     public Connection getConnection(){
  72.         Connection conn = null;
  73.         try{
  74.             DataSource ds = localhost();
  75.             conn = ds.getConnection();
  76.             }
  77.         catch(Exception e){
  78.             e.printStackTrace();
  79.             }
  80.         return conn;
  81.         }
  82.     /**
  83.      * 关闭连接
  84.      * @param null
  85.      * @return  null
  86.      * @since 1.2
  87.      * */
  88.     public static void close(Connection conn){
  89.         try{
  90.             if(conn != null)
  91.                 conn.close();
  92.             }
  93.         catch(SQLException e){
  94.             e.printStackTrace();
  95.             }
  96.         }
  97.     /**
  98.      * 执行查询操作
  99.      * @param sql
  100.      * @return ResultSet
  101.      * */
  102.     public  CachedRowSet executeQuery(String sql)
  103.     {  
  104.         Connection conn=null;
  105.         CachedRowSet rs=null;
  106.         try{
  107.             rs=new CachedRowSet();
  108.             conn=getConnection();
  109.             Statement stmt=conn.createStatement();
  110.             ResultSet rs1=stmt.executeQuery(sql);
  111.             rs.populate(rs1);
  112.             }
  113.         catch(Exception e) {
  114.             System.out.println(e.toString());  
  115.             }
  116.         finally{
  117.             try{
  118.                 conn.close();
  119.                 }
  120.             catch(Exception ex){}
  121.             }
  122.         return rs;
  123.         }
  124.     /**
  125.      * 执行数据的插入、删除、修改操作
  126.      * @param sql
  127.      * @return boolean
  128.      * */
  129.     public  boolean executeUpdate(String sql){
  130.         boolean bl;
  131.         bl = false;
  132.         Connection conn = getConnection();
  133.         try{
  134.             Statement stmt = conn.createStatement();
  135.             if(stmt.executeUpdate(sql) > 0)
  136.                 stmt.close();
  137.             bl = true;
  138.             }
  139.         catch(SQLException e){}
  140.         finally{
  141.             close(conn);
  142.             }
  143.         return bl;
  144.         }
  145.     /**
  146.      * 获得数据库JNDI名称
  147.      * @param null
  148.      * @return String
  149.      * */
  150.     public String getjndiName(){
  151.         return this.jndiName;
  152.     }
  153.     /**
  154.      * 设置数据库JNDI名称
  155.      * @param jndiName
  156.      * @return true|false
  157.      * */
  158.     public boolean setjndiName(String jndiName){
  159.         this.jndiName = jndiName;
  160.         return true;
  161.         }
  162. }
复制代码


第三步: 编写test.jsp测试
  1. <%@ page language="java" contentType="text/html; charset=gbk"
  2.     pageEncoding="gbk"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  4. "http://www.w3.org/TR/html4/loose.dtd">
  5. <%@page import="withouttears.bean.Database"%>
  6. <%@page import="java.sql.*"%>
  7. <html>
  8. <head>
  9. <meta http-equiv="Content-Type" content="text/html; charset=gbk">
  10. <title>Insert title here</title>
  11. </head>
  12. <body>
  13. <%
  14. Database db=new Database();
  15. db.setjndiName("jdbc/testdb");//初始化JNDI名称
  16. ResultSet rs=db.executeQuery("select * from test_table");
  17. while(rs.next()){
  18.         out.println("id:"+rs.getInt("id")+"<br>");
  19. }
  20. rs.close();
  21. %>
  22. </body>
  23. </html>
复制代码

好了,打开浏览器输入:http://localhost:8080/test.jsp

[ 本帖最后由 wiThouTTears 于 2006-12-19 15:56 编辑 ]
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP