测试代码如下:
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;
}
}
}