1.Tomcat5.5连接池配置
1.1 配置server.xml文件 核心部分
<Host appBase="webapps" name="localhost">
<Context docBase="shopping[T1] " crossContext="true" path="/shopping" debug="0" reloadable="true">
<Resource
name="jdbc/shopping"
type="javax.sql.DataSource"
password=""
driverClassName="com.mysql.jdbc.Driver"
maxIdle="2"
maxWait="5000"
username="root"
url="jdbc:mysql://localhost:3306/Shopping"
maxActive="4"/>
</Context>
</Host>
2. 数据库连接代码
package com.shopping.dbc;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DBConnection {
// 数据库加载驱动
private static final String driver [T2] = "com.mysql.jdbc.Driver";
// 数据库访问URL
private static final String URL = "jdbc:mysql://localhost:3306/Shopping";
// 数据库访问用户名
private static final String username = "root";
// 数据库访问密码
private static final String password = "";
// 数据库连接
private static Connection con = null;
// 获得数据库连接
public static synchronized [T3] Connection getConnection() throws Exception {
try {
// 获得JNDI初始化上下文
InitialContext ctx = new InitialContext();
// 在JNDI命名空间java:comp/env段里获得上下文对象 并通过JNDI名获得数据源对象
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/sh");
con = ds.getConnection();
} catch (NamingException e) {
try {
// 加载数据库驱动程序
Class.forName(driver).newInstance();
// 获得数据库连接
con = DriverManager.getConnection(URL, username, password);
} catch (ClassNotFoundException ex) {
System.out.println("数据库驱动加载异常:" + ex.getMessage());
}
}
return con;
}
public static void main(String args[]) throws Exception {[T4]
if (DBConnection.getConnection() != null) {
System.out.println("Connection is ok....");
} else {
System.out.println("Connection is fail..");
}
}
}
评论