TOMCAT连接池

实际上MySQL和SQL SERVER 两种数据库连接方式非常非常类似

编码格式使用 URIEncoding="UTF-8" 各位应更具自己的需要设置成GBK或者GB2312,但我个人强烈建议全部统一为 UTF-8



先例举MySQL数据连接池设置:



1.将 mysql 的驱动文件mysql.jar复制到tomcat/lib录

2.编辑 web 应用中的目录 META-INF/context.xml 文件,内容如下

<Context path="/webapp" URIEncoding="UTF-8">
<Resource name="jdbc/myjdbc"
auth="Container"
description="DB Connection"
driverClassName="com.mysql.jdbc.Driver"
maxActive="500"
maxIdle="30"
maxWait="10000"
type="javax.sql.DataSource"
username="sqluser1"
password="123456"
url="jdbc:mysql://192.168.1.2:3306/mydb?autoReconnect=true"
/>
</Context>



webapp:你的应用名称

mydb:MySQL 内 Database 的名称

com.mysql.jdbc.Driver:所使用的驱动,来自倒入的 mysql 的 jar 文件


3.编辑 web 应用中的目录 WEB-INF/web.xml 内容如下



<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/myjdbc</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>



至此,针对 MySQL 的数据连结池配置完成



例举 SQL SERVER 数据连接池设置:



1.将 sqlserver 的驱动文件 sqljdbc.jar 复制到 tomcat/lib 录

2.编辑 web 应用中的目录 META-INF/context.xml 文件,内容如下

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/webapp1" URIEncoding="UTF-8">
<Resource
description="DB Connection"
driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
maxActive="500"
maxIdle="30"
maxWait="10000"
name="jdbc/msjdbc"
auth="Container"
type="javax.sql.DataSource"
username="sqluser2"
password="123456"
url="jdbc:sqlserver://localhost:1433;databaseName=mydb"
/>
</Context>
3.编辑 web 应用中的目录 WEB-INF/web.xml 内容如下

<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/msjdbc</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

至此,针对 SQL SERVER 的数据连结池配置完成,使用微软JDBC1.2版本,同时兼容2000和2005,本人实际测试通过。



连接池调用部分代码如下:



import java.sql.*;
import javax.sql.*;



...

...



Connection con;
Statement stmt;
ResultSet rs;

try
{
// 连接数据库
Context ctx = new InitialContext ();


// 以下两种连接方式根据连接MySQL还是SQLSERVER来决定采用

DataSource ds = (DataSource) ctx.lookup ("java:comp/env/jdbc/myjdbc"); // MySQL 使用

DataSource ds = (DataSource) ctx.lookup ("java:comp/env/jdbc/msjdbc"); // SQLSERVER 使用


con = ds.getConnection ();
// 创建 JDBC 申明
stmt = con.createStatement ();

try
{

// SQL 命令构建

String SqlCmdText = "select * from message_text";

// 执行SQL命令

rs = stmt.executeQuery (sqlCmdSelect);

// 遍历所有记录

where ( rs.next()

{

String OutText = rs.getString("fieldname");

......

......
}

// 资源释放
if ( rs != null )
{
rs.close ();
}


}
catch (Exception e)
{
}

// 资源释放

if (stmt != null)
{
stmt.close ();
}
if (con != null)
{
con.close ();
}
}
catch (Exception e)
{
}


// 完成
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值