1、 在项目中新建context.xml文件,不要在tomcat服务器的目录中修改context.xml(会对整个服务器生效)。。 在web项目的META-INF中存放context.xml
2、在文件进行配置::: 配置数据库连接池的技术
<?xml version='1.0' encoding='utf-8'?>
<Context>
<Resource
driverClassName="com.mysql.jdbc.Driver" mysql驱动包
url="jdbc:mysql://localhost:3306/ssm" 连接
username="root" 账号
password="" 密码
maxActive="" 最大连接数量
maxIdle="" 等待连接的数量
name="test" 连接池的名称
auth="Container" 谁来管理(Container是tomcat服务器)
maxWait="" 超过10秒连接不上就报异常
type="javax.sql.DataSource" 这是java中专门的为连接数据库创建的类型
/>
</Context>
3、通过连接池进行连接,获取连接对象
package com.bjsxt.servlet; import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
@WebServlet("/test")
public class DemoServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
Context cxt=new InitialContext(); Context是上下文接口 context.xml文件对象类型
DataSource ds = (DataSource) cxt.lookup("java:comp/env/test");本地数据库环境 (java:comp/env/这是固定字符串) test是自配置的连接池
Connection conn = ds.getConnection(); 25-27行是JNDI代码
PreparedStatement ps=conn.prepareStatement("select * from flower");
resp.setContentType("text/html;charset=utf-8");
ResultSet rs=ps.executeQuery();
PrintWriter out = resp.getWriter();
while(rs.next()){
out.print(rs.getInt()+" "+rs.getString());
}
out.flush();
out.close(); 当关闭连接对象时,把连接对象归还给数据库连接池,把状态改变成idle
并不是关闭
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
}