在tomcat下配置数据源
1:启动tomcat
2:进入Tomcat Administration (http://localhost:8080/admin)以admin身份登陆
3:点击左栏 Tomcat Server>>>Service>>>Host(点击Service前面的小黑点而得)>>>你的Webapp的Context>>>Resources>>>Data Sources
4:在右栏的Data Source Actions 下拉框中选择 Create New Data Source>>>然后配置DataSource信息
以SQL Server 2000 为例:
JNDI Name: jdbc/bn
Data Source URL: jdbc:microsoft:sqlserver://localhost:1433;databaseName=guestbook JDBC Driver Class:com.microsoft.jdbc.sqlserver.SQLServerDriver
User Name:sa
Password: 12345678 Max. Active Connections: 4
Max. Active Connections: 2
Max. Wait for Connection: 5000
Validation Query://可以不填
5、点击Save按钮>>>点击页头的 Commit Changes按钮
6、重新启动服务,在测试页面中输入如下代码
<%@ page language="java" contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*,java.io.*"%>
<%@ page import="javax.sql.*"%>
<%@ page import="javax.naming.*"%>
<%String name;%>
<html>
<head>
<title>CyberCreations</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
.....
使用tomcat连接池 来连接数据库:<hr>
<table border=1>
<tr><td>ID</td><td>名字</td><td>邮箱</td><td>上次登陆时间</td></tr>
<%
DataSource ds = null;
Context initctx = new InitialContext();
Context envctx = (Context) initctx.lookup("java:comp/env");
ds=(DataSource)envctx.lookup("jdbc/bn");
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from user_info");
while(rs.next()) {
out.println("<tr>");
out.println("<td>" + rs.getString("userId") + "</td>");
out.println("<td>" + rs.getString("name") + "</td>");
out.println("<td>" + rs.getString("email") + "</td>");
out.println("<td>" + rs.getDate("userLastLogTime") + "</td>");
out.println("</tr>");
}
%>
</table>
</body>
</html>