关闭

tomcat配置数据源

210人阅读 评论(0) 收藏 举报

最近想搞清楚什么是“连接池”,在网上查了相关资料,貌似要跟“服务器”中配置,

 

 

1、首先在WebRoot/META-INF目录下面建立一个context.xml配置文件,内容如下

<?xml version="1.0" encoding="UTF-8"?>
<Context>

	<WatchedResource>WEB-INF/web.xml</WatchedResource>

	<Resource 
	name="myoracle" 
	auth="Container" 
	type="javax.sql.DataSource"
	driverClassName="oracle.jdbc.OracleDriver" 
	url="jdbc:oracle:thin:@localhost:1521:orcl"
	username="huangbiao" 
	password="huangbiao" 
	maxActive="200" 
	maxIdle="10" 
	maxWait="5000" />

</Context>

 

2、启动tomcat服务器(如果启动失败,可能原因是没有驱动,需要在tomcat的lib目录下面放驱动包)

 

3、在servlet中得到得到数据源,操作数据库

 

package hb.servlet.dbpool;

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.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

public class ConnectDB extends HttpServlet {

	public static Logger log = Logger.getLogger(ConnectDB.class);
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		log.info("发送请求成功");
		try {
			InitialContext ic = new InitialContext();
			DataSource ds = (DataSource)ic.lookup("java:comp/env/myoracle");
			Connection conn = ds.getConnection();
			String sql = "select * from goods where GOODSNAME=?";
			PreparedStatement pre = conn.prepareStatement(sql);
			pre.setString(1, "7001");
			ResultSet rs = pre.executeQuery();
			while(rs.next()){
				 log.info(rs.getString(1));
				 log.info(rs.getString(2));
				 log.info(rs.getInt(3));
				 log.info(rs.getString(4));
				 log.info(rs.getString(5));
			}
			if(rs != null){
				log.info("关闭rs正常");
				rs.close();
			}
			if(pre != null){
				log.info("关闭pre正常");
				pre.close();
			}
			if(conn != null){
				log.info("关闭conn正常");
				conn.close();
			}
			PrintWriter pw = response.getWriter();
			String result = "操作数据库OK";
			pw.write(new String(result.getBytes("utf-8"),"ISO-8859-1"));
			pw.flush();
			
		} catch (NamingException e) {
			log.error("获取连接池异常");
			e.printStackTrace();
		} catch (SQLException e) {
			log.error("操作数据库失败");
			e.printStackTrace();
		}
	}

}

 

 

在这里我有一些不明白的地方:

1、这种方式算是“使用连接池”吗

2、conn.close()这种方式关闭了是断开了数据源吗

请路过的高手指点一二

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:286110次
    • 积分:8489
    • 等级:
    • 排名:第2296名
    • 原创:1096篇
    • 转载:14篇
    • 译文:0篇
    • 评论:4条
    最新评论