javaBean+tomcat+MySql数据库连接池三步曲(原创)

本文介绍如何使用JSP和Tomcat配置数据库连接池,并通过JavaBean实现数据库的读取操作。包括配置步骤、代码示例及测试方法。

最近学习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。

< Context >
        
< Resource  name ="jdbc/testdb"  
        auth
="Container"  
        type
="javax.sql.DataSource"  
        driverClassName
="com.mysql.jdbc.Driver"  
        url
="jdbc:mysql://localhost/mytestdb"  
        username
="root"  
        password
="******"  
        maxActive
="100"  
        maxIdle
="30"  
        maxWait
="10000"  
        
></ Resource >  
</ Context >

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

 

package  withouttears.bean;

import  java.util.HashMap;
import  java.sql. * ;
// JNDI有两个核心接口Context和DirContext,
// Context中包含了基本的名字操作,而DirContext则将这些操作扩展到目录服务。
import  javax.naming.Context;
import  javax.naming.InitialContext;
// 数据库资源的连接工厂是javax.sql.DataSource对象,
// 它可以创建java.sql.Connection数据库连接对象。
import  javax.sql.DataSource;
// 目前您可以从Java开发者连接http://java.sun.com/products/jdbc/download.html#rowsetcobundle1_0  
// 下载CachedRowSet的实现。下载并解压缩安装文件后,将"rowset.jar"文件放到您的类目录下。
// CachedRowSet在sun.jdbc.rowset包中。
import  sun.jdbc.rowset.CachedRowSet;
/**
* <b>类</b>: DataBase<br>
* <b>版本</b>: 1.0.0<br>
* <b>作者</b>: wiThouTTears<br>
* <b>时间</b>: 2006-12-18<br>
* <b>QQ</b>: 314765755<br>
* <b>Email</b>: wiThouT--Tears@163.com<br>
* <b>Blog</b>: 
http://blog.youkuaiyun.com/withouttears/<br>
* <b>功能</b>: 用连接池连接MySql数据库及相关操作<br>
*/

public   class  Database  {
    
/**
     * 数据库JNDI名称,默认:jdbc/testdb
     * 
*/

    
private String jndiName="jdbc/testdb";
    
/**
     * 建立连接池
     * 
@param null
     * 
@return DataSource
     * 
*/

    
private DataSource localhost(){
        DataSource ds
=null;
        
//在HashMap中通过get()来获取value,通过put()来插入value,
        
//ContainsKey()则用来检验对象是否已经存在
        HashMap<Object,Object> cachedDs=new HashMap<Object,Object> ();
        
if(cachedDs.containsKey("ds"))//取出空闲状态的数据库连接
            {
                
/* 在DataSource中事先建立了多个数据库连接,
                 * 这些数据库连接保存在连接池(Connect Pool)中。
                 * Java程序访问数据库时,只需要从连接池中取出空闲状态的数据库连接;
                 * 当程序访问数据库结束,再将数据库连接放回连接池。
                 * 
*/

                ds 
= (DataSource)cachedDs.get("ds");
            }

        
else
            
try
            
{
                    
/*在javax.naming包中提供了Context接口,
                     * 该接口提供了将对象和名字绑定,以及通过名字检索对象的方法。
                     * 
*/

                Context initCtx 
= new InitialContext();
                
//lookup(String name):返回与指定的名字绑定的对象,获得数据库连接工厂
                ds = (DataSource)initCtx.lookup("java:comp/env/"+getjndiName());
                cachedDs.put(
"ds", ds);
            }

            
catch(Exception e)
            
{
                e.printStackTrace();
            }

                
return ds;
        }

    
/**
     * 库的连接
     * 
@param null
     * 
@return Connection
     * 
*/

    
public Connection getConnection(){
        Connection conn 
= null;
        
try{
            DataSource ds 
= localhost();
            conn 
= ds.getConnection();
            }

        
catch(Exception e){
            e.printStackTrace();
            }

        
return conn;
        }

    
/**
     * 关闭连接
     * 
@param conn
     * 
@return null
     * 
@since 1.2
     * 
*/

    
public static void close(Connection conn){
        
try{
            
if(conn != null)
                conn.close();
            }

        
catch(SQLException e){
            e.printStackTrace();
            }

        }

    
/**
     * 执行查询操作
     * 
@param sql
     * 
@return ResultSet
     * 
*/

    
public CachedRowSet executeQuery(String sql)
    

        Connection conn
=null;
        CachedRowSet rs
=null;
        
try{
            rs
=new CachedRowSet();
            conn
=getConnection(); 
            Statement stmt
=conn.createStatement();
            ResultSet rs1
=stmt.executeQuery(sql);
            rs.populate(rs1);
            }

        
catch(Exception e) {
            System.out.println(e.toString()); 
            }

        
finally{
            
try{
                conn.close(); 
                }

            
catch(Exception ex){}
            }

        
return rs;
        }

    
/**
     * 执行数据的插入、删除、修改操作
     * 
@param sql
     * 
@return boolean
     * 
*/

    
public boolean executeUpdate(String sql){
        
boolean bl;
        bl 
= false;
        Connection conn 
= getConnection();
        
try{
            Statement stmt 
= conn.createStatement();
            
if(stmt.executeUpdate(sql) > 0)
                stmt.close();
            bl 
= true;
            }

        
catch(SQLException e){}
        
finally{
            close(conn);
            }

        
return bl;
        }

    
/**
     * 获得数据库JNDI名称
     * 
@param null
     * 
@return String
     * 
*/

    
public String getjndiName(){
        
return this.jndiName;
    }

    
/**
     * 设置数据库JNDI名称
     * 
@param jndiName
     * 
@return true|false
     * 
*/

    
public boolean setjndiName(String jndiName){
        
this.jndiName = jndiName;
        
return true;
        }

}

第三步: 编写test.jsp测试

<% @page  import = " withouttears.bean.Database " %>
<% @page  import = " java.sql.* " %>
< html >
< head >
< meta http - equiv = " Content-Type "  content = " text/html; charset=gbk " >
< title > Insert title here </ title >
</ head >
< body >
<%
Database db
= new  Database();
db.setjndiName(
" jdbc/testdb " ); // 初始化JNDI名称

ResultSet rs
= db.executeQuery( " select * from test_table " );
while (rs.next()) {
        out.println(
"id:"+rs.getInt("id")+"<br>");
}

rs.close();
%>
</ body >
</ html >

好了,打开浏览器输入:http://localhost:8080/test.jsp,在Windows2000Pro+tomcat5.5.7下通过。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值