一、首先新建文件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错误。