eclipse下老师教的连接池的配置

1.确定tomcat lib文件夹下有mysql链接文件

2.写入context.xml文件 位置如图

<Context>
    <Resource name="jdbc/registration"
        auth="Container" type="javax.sql.DataSource"
        maxActive="100" maxIdle="30" maxWait="10000"
        username="root" password="123456"
        driverClassName="com.mysql.jdbc.Driver"
        url="jdbc:mysql://localhost:3306/java_web?useUnicode=true&amp;characterEncoding=utf-8"/>
</Context>

3.配置web.xml文件 位置如图

  <resource-ref>
    <res-ref-name>jdbc/registration</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
 </resource-ref> 

图中标注请保持一致

4.新建test.jsp文件测试

假设有如下数据库和表


新建test.jsp

内容如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import="javax.sql.*" %>
<%@ page import="javax.naming.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>test</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;

try {
    Context initContext = new InitialContext();
    DataSource ds = (DataSource)initContext.lookup("java:/comp/env/jdbc/registration");
    conn = ds.getConnection();
    
    pstmt = conn.prepareStatement("select * from card_user");
//  pstmt.setString(1, username);
    //execute: boolean
    //executeQuery: ResultSet
    //executeUpdate: int
    rs = pstmt.executeQuery();
    while(rs.next()) {
        String name = rs.getString("username");
        String pwd = rs.getString("password");
        out.println(name);
        out.println(pwd);
    }
}catch (Exception e) {
    e.printStackTrace();
} finally {
    if(rs!=null){
        rs.close();
    }
    if(pstmt!=null){
        pstmt.close();
    }
    if(conn!=null){
        conn.close();
    }
    //rs
    //pstmt
    //conn
}
%>
</body>
</html>

运行效果

在tomcat运行
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容