版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/aduovip/article/details/71076317
本博文 给出一个使用数据库连接池的例子, 将使用webdb 数据源 获取一个MySQL 数据库连接,并查询其中的t_dirctionary表, 最后将查询结果显示在客户端浏览器。
以下ViewDictionary 类 演示了怎么样 使用数据库连接池获取数据库连接, 代码如下:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ViewDictionary extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try{
javax.naming.Context ctx = new javax.naming.InitialContext();
// 根据webdb数据源获得DataSource对象
javax.sql.DataSource ds = (javax.sql.DataSource) ctx
.lookup("java:/comp/env/jdbc/webdb");
Connection conn = ds.getConnection();
// 执行SQL语句
PreparedStatement pstmt = conn
.prepareStatement("SELECT * FROM t_dictionary");
ResultSet rs = pstmt.executeQuery();
StringBuilder table = new StringBuilder();
table.append("<table border='1'>");
table.append("<tr><td>书名</td><td>价格</td></tr>");
while (rs.next()){ // 生成查询结果
table.append("<tr><td>" + rs.getString("english") + "</td><td>");
table.append(rs.getString("chinese") + "</td></tr>");
}
table.append("</table>");
out.println(table.toString()); // 输出查询结果
pstmt.close(); // 关闭PreparedStatement对象
}catch (Exception e){
out.println(e.getMessage());
}
}
}
1. 要从数据源 中获得数据库连接对象, 需要使用javax.naming.Context 的lookup方法。
2. 在应用程序中通过数据源连接池连接数据库时,除了通过数据源获取数据库 连接的步骤, 其他步骤 和直接使用 JDBC操作数据库是完全一样的.
到现在,需要建立数据库webdb, 建立数据表t_dictionary, 并且往该表中插入数据。
要查看上述代码的效果, 可以在浏览器的地址栏中输入如下url:
http://localhost:8080/webdemo/servlet/ViewDictionary