Tomcat连接池配置

Tomcat连接池配置+myeclipse

首先配置tomcat 中的配置文件 (试用于全局性的资源)

tomcat--conf--context.xml 

例1:在context中配置

<Environment name="news" value="hello JNDI" type="java.lang.String"/>

在jsp中使用,通过Context的实例的lookup方法找到news这个名字并将其value值读取出来。

<%
    Context ctx =new InitialContext(); 
    String testjndi=(String)ctx.lookup("java:comp/env/news");  
    out.println(testjndi);
    
     %>

例子2:配置数据库

通过tomcat的连接,则需要将原项目lib中的jar包方到tomcat的lib中。(注意区分mysql和mssql不同的jar包)

在context中添加一下代码,name是自定义的其他是固定用法。

<Resource name="jdbc/demo"
      auth="Container"
     type="javax.sql.DataSource"
       maxActive="100"
      maxIdle="30"
      maxWait="10000"
       username="root"
       password="root"
      driverClassName="com.mysql.jdbc.Driver"
      url="jdbc:mysql://localhost:3306/test?autoReconnect=true"/>

一下是具体的使用,context------source.getConnection();其他部分与数据库直接操作相同。这一段例子是查询user表中name字段并显示出来。

 <%
    Connection connection = null;
	PreparedStatement titlesQuery = null;
	ResultSet rs = null;
	try {
		Context ic = new InitialContext();
		DataSource source = (DataSource) ic
				.lookup("java:comp/env/jdbc/demo");
		connection = source.getConnection();
		titlesQuery = connection
				.prepareStatement("SELECT *  FROM user ");
		rs = titlesQuery.executeQuery();
		if (rs!=null){
		  while(rs.next()){
		    out.println(rs.getString("name"));
		    out.println("<br/>");
		  }
		}         
	} catch (SQLException exception) {
		exception.printStackTrace();
	} catch (NamingException namingException) {
		namingException.printStackTrace();
	} finally {
		if (rs != null)
			rs.close();
		if (titlesQuery != null)
			titlesQuery.close();
		if (connection != null)
			connection.close();
	}     
   %>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值