日期:2014-05-16  浏览次数:20466 次

用QueryRunner读取数据库的内容,每个对象代表一条记录来读取

package cn.com.jobedu.blog;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

public class GetBlogServlet extends HttpServlet {

?private static final long serialVersionUID = -7152478870507997462L;

?public void doGet(HttpServletRequest request, HttpServletResponse response)
???throws ServletException, IOException {
??DataSource ds = null;
??String id = request.getParameter("id");
??try {
???InitialContext context = new InitialContext();
???ds = (DataSource) context.lookup("java:/comp/env/jdbc/mysqlds");
??} catch (Exception e) {
???System.out.println("获取数据源时出错");
??}
??try {
???String sql = "select id, title, content, createdtime from blog where id="
?????+ id;
???QueryRunner qr = new QueryRunner(ds);
???List list = (List) qr.query(sql, new BeanListHandler(Blog.class));?//Blog类中提供get和set方法
???Blog blog = (Blog) list.get(0);
???
???System.out.println(blog.getId());
???System.out.println(blog.getTitle());
???System.out.println(blog.getContent());
???System.out.println(blog.getCreatedTime());
???

??} catch (SQLException e) {
???e.printStackTrace();
??}
??

??//request.setAttribute("message", message);
??//request.getRequestDispatcher("/addBlogResult.jsp").forward(request,response);
?}
}