jdbc连接池及配置

 

一、首先新建文件content.xml,以及进行配置
在META-INF文件夹下新建content.xml文件,内容为数据库连接的配置
<Context>
    <Resource
    name="jdbc/myjsp"
    type="javax.sql.DataSource"
    password="sa"
    driverClassName="com.mysql.jdbc.Driver"
    maxIdle="5"
    maxWait="5000"
    username="root"
    url="jdbc:mysql://localhost:3306/test"
    maxActive="10"/>
</Context>

二、然后在web.xml添加调用
<web-app>
<resource-ref>
<res-ref-name>jdbc/myjsp</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>

三、创建连接池类:

package com.webdemo.util;


import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import javax.sql.DataSource;


public class dbpool
   {
private Context initCtx = null;
private Context ctx=null;
private DataSource ds=null;
private Connection conn=null;
/**
*
*/
public dbpool()
{
   try {
    //
    initCtx= new InitialContext();
    ctx=(Context)initCtx.lookup("java:comp/env");
    ds=(DataSource)ctx.lookup("jdbc/myjsp");
   
   } catch (NamingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
}
/**
   * ??
   */
public Connection getconnection()
{
   try
   {
    //
     conn=ds.getConnection();
    return conn;
   }
   catch(Exception ex)
   {
    System.out.print(ex.getMessage());
    return null;
   }
}
  
/**
   *
   */
public void FreeConnection()
{
    if(conn!=null)
    {
     try
     {
       conn.close();
     }
     catch(Exception ex)
     {

      System.out.print(ex.getMessage());
     }
    }
  
  
}

   }


四、调用连接池类进行数据操作
public class EditBean
{
public void UpdateUser(String name,String sex,Date birth,String birthaddr)
{
   PreparedStatement pStmt = null;
   try
   {
    //打开数据连接池
    dbpool dbpool=new dbpool();
    Connection conn=dbpool.getconnection();
    pStmt = conn.prepareStatement("insert into metable(name, sex, birth)"
      + " values(?, ?, ?, ?)");
    conn.setAutoCommit(false);
    pStmt.setString(1, name);
    pStmt.setString(2, sex);
    pStmt.setTime(3, (Time) birth);
    pStmt.executeUpdate();
    conn.commit();
    System.out.println("插入一条新记录!");
   }
   catch(Exception ex)
   {
    System.out.print(ex.getMessage());
   }
}
注:jboss服务器下的连接池配置并非如此,使用此方法进行配置,将出现404错误。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值