Tomcat配置数据库、连接池、数据源

1、首先导入JDBC驱动。
2、更改context.xml文件
<?xml version='1.0' encoding='utf-8'?>
<Context reloadable="true">
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
maxActive
="100" maxIdle="30" maxWait="10000"
username
="root" password="3.14" driverClassName="com.mysql.jdbc.Driver"
url
="jdbc:mysql://localhost:3306/test"/>
</Context>
3、代码
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;


try {
Connection conn=null;
Context context = new InitialContext();
DataSource ds = (DataSource)context.lookup("java:/comp/env/jdbc/TestDB");
conn=ds.getConnection();

PreparedStatement pstmt=conn.prepareStatement("select * from person");
ResultSet rs=(ResultSet) pstmt.executeQuery();
while(rs.next()){
out.println(rs.getString("username"));
out.println("-----------------");
}
rs.close();
pstmt.close();
conn.close();
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
 
 
1 <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
3 <sql:query var="rs" dataSource="jdbc/TestDB">select * from person
4 </sql:query>
5 <c:forEach var="row" items="${rs.rows}">
6 username ${row.username}:password ${row.password}<br/>
7 </c:forEach>
posted @ 2012-03-23 23:40  蕭慶蘋  阅读(156)  评论(0编辑  收藏  举报