javabean调用tomcat连接池

测试代码如下:

package com.snail.jdbc;

import java.sql.*;
import javax.sql.*;
import javax.naming.*;

public class TestConPool {

 /**
  * 测试javabean调用tomcat连接池
  *
  * @param args
  */
 Connection conn = null;
 Statement stmt = null;

 // 构建数据库连接池
 public TestConPool() {
  DataSource source = null;
  try {
   InitialContext ctx=new InitialContext();
   source=(DataSource)ctx.lookup("java:comp/env/jdbc/mydatasource");
   conn = source.getConnection();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 /**
  * executeQuery操作,用于数据查询,主要是Select
  *
  * @param sql
  *  查询字段
  * @return 数据集
  * @throws SQLException
  *  捕捉错误
  */
 public StringBuffer executeQuery() throws SQLException {
  StringBuffer buffer = new StringBuffer();
  ResultSet rs = null;
  String sql = "select city from authors";
  try {
   stmt = conn.createStatement();
   rs = stmt.executeQuery(sql);
   buffer.append("<table border>");
   buffer.append("<tr>");
   buffer.append("<th width=100>" + "city");
   buffer.append("</tr>");
   
   while(rs.next()){
    
    buffer.append("<tr>");
    buffer.append("<td>" + rs.getString(1) + "</td>");
    System.out.println(rs.getString(1));
    buffer.append("</tr>");
    
   }
   
   buffer.append("</table>");
   
   buffer.append("<br>");
   
  } catch (SQLException ex) {
   ex.printStackTrace();
   System.out.println("executeQuery:" + ex.getMessage());
   throw ex;
  }
  return buffer;
 }

 /**
  * 关闭对象
  *
  * @throws SQLException
  *  捕捉错误
  */
 public void close() throws SQLException {
  if (stmt != null){
   stmt.close();
   stmt = null;
  }
  if (conn != null){
   conn.close();
   conn = null;
  }

 }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值