Java Web开发7___通过数据库连接池连接MySQL 数据库

来源:互联网 发布:基本编程 编辑:程序博客网 时间:2024/06/11 11:57

本博文 给出一个使用数据库连接池的例子, 将使用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

0 0