《JDBC访问数据库.docx》由会员分享,可在线阅读,更多相关《JDBC访问数据库.docx(9页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、实验十 JDBC访问数据库一 实验目的1. 掌握使用传统的方法访问数据库;2. 掌握使用数据源的方法访问数据库。二 实验内容任务1:使用传统方法通过Servlet访问数据库步骤1:创建数据库在MySQL创建一个名为postgres的数据库,用户名为root,口令为j2ee。在其中建立books表,代码如下:CREATE DATABASE postgres;USE postgres;CREATE TABLE books ( bookid character(5) PRIMARY KEY, -书号 title text, -书名author character varying(20), -作者 p
2、ublisher character varying (40), -出版社 price double precision -价格);步骤2:向books表中插入下面几条记录,代码如下:INSERT INTO books VALUES (204,Head First Servlets & JSP, Bryan Basham, 中国电力出版社,98.00);INSERT INTO books VALUES (201, Servlets 与JSP 核心教程, Hall Marty,清华大学出版社,45);INSERT INTO books VALUES (202, Tomcat与Java Web 开
3、发技术祥解, 孙卫琴, 机械工业出版社,45);INSERT INTO books VALUES (203, JSP 应用开发技术, 柳永坡,人民邮电出版社,52);INSERT INTO books VALUES (205, J2EE 1.4 编程指南, Spielman Sue,电子工业出版社,68);步骤3:将MySQL数据库的JDBC驱动程序安装到应用程序的WEB-INFlib目录中。步骤4:在com.demo包中创建BookBean类用来存储一本书信息,该类包含下面5个属性,请定义无参数构造方法和带参数构造方法,为每个属性定义访问方法(getter)和修改方法(setter)。该类属
4、性如下,这些属性与books表的字段对应:private String bookid;private String title;private String author;private String publisher;private double price;步骤5:编写下面JSP页面bookQuery.jsp用来输入书号页面,代码如下:图书查询 请输入书号: 查询所有图书该页面显示结果如图所示:图 9.1 bookQuery.jsp页面显示结果步骤6:在com.demo包中编写下面的BookQueryServlet连接数据库,查询图书信息,转发请求到displayBook.jsp或err
5、or.jsp页面。package com.demo;import java.io.IOException;import javax.servlet.*;import javax.servlet.annotation.WebServlet;import javax.servlet.http.*;import java.sql.*;WebServlet(/BookQueryServlet)public class BookQueryServlet extends HttpServlet private static final long serialVersionUID = 1L; Connect
6、ion dbconn;BookBean book = new BookBean(); public void init() String driver = com.mysql.jdbc.Driver;String dburl = jdbc:mysql:/localhost:3306/postgres;String username = postgres;String password = postgres;try /加载数据库驱动程序Class.forName(driver); /创建数据库连接对象 dbconn = DriverManager.getConnection( dburl,use
7、rname,password);catch(ClassNotFoundException cfe) log(Exception:+cfe);catch(SQLException sqle) log(Exception:+sqle); public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException String bookid = request.getParameter(bookid); try String sql=SELECT * F
8、ROM books WHERE bookid=?; PreparedStatement pstmt = dbconn.prepareStatement(sql); pstmt.setString(1,bookid); ResultSet rst = pstmt.executeQuery(); if(rst.next() book.setBookid(rst.getString(bookid); book.setTitle(rst.getString(title); book.setAuthor(rst.getString(author); book.setPrice(rst.getFloat(
9、price); book.setPublisher(rst.getString(publisher); request.getSession().setAttribute(book, book); RequestDispatcher view = request.getRequestDispatcher(/displayBook.jsp); view.forward(request, response); else RequestDispatcher view = request.getRequestDispatcher(/error.jsp); view.forward(request, r
10、esponse); catch(SQLException e) e.printStackTrace(); public void destroy()try dbconn.close();catch(Exception e) e.printStackTrace();步骤7:编写下面JSP页面displayBook.jsp用来显示图书信息,error.jsp页面显示错误信息。书号: 书名: 作者:出版社:价格:error.jsp页面如下: 该书不存在。返回任务2:通过数据源访问数据库步骤1:建立局部数据源。将下面的代码放到Tomcat 的confcontext.xml中,重启Tomcat:注意:需
11、要将数据库的JDBC驱动程序安装到WEB-INFlib目录中,并重新启动Tomcat服务器。步骤2:在com.demo包中编写下面的BookQueryServlet2连接数据库,查询图书信息,转发请求到displayBook.jsp或error.jsp页面。package com.demo;import java.io.*;import java.sql.*;import javax.servlet.*;import javax.servlet.http.*;import com.demo.BookBean;import javax.sql.DataSource;import javax.na
12、ming.*;import javax.servlet.annotation.WebServlet;WebServlet(/BookQueryServlet2)public class BookQueryServlet2 extends HttpServlet Connection dbconn; public void init() try Context context = new InitialContext(); DataSource ds = (DataSource)context.lookup(java:comp/env/jdbc/sampleDS); dbconn = ds.ge
13、tConnection(); catch(NamingException ne) log(Exception:+ne); catch(SQLException se) log(Exception:+se); public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException String bookid = request.getParameter(bookid); try String sql=SELECT * FROM books WHE
14、RE bookid=?; PreparedStatement pstmt = dbconn.prepareStatement(sql); pstmt.setString(1,bookid); ResultSet rst = pstmt.executeQuery(); if(rst.next() BookBean book = new BookBean(); book.setBookid(rst.getString(bookid); book.setTitle(rst.getString(title); book.setAuthor(rst.getString(author); book.set
15、Price(rst.getDouble(price); book.setPublisher(rst.getString(publisher); request.getSession().setAttribute(book, book); response.sendRedirect(/helloweb/displayBook.jsp); elseresponse.sendRedirect(/helloweb/error.jsp); catch(SQLException e) e.printStackTrace(); public void destroy()try dbconn.close();
16、catch(Exception e)e.printStackTrace();其他类和JSP页面与任务1相同,无需修改。访问bookQuery.jsp,结果与任务1相同。任务3:综合应用。本实验采用MVC设计模式,通过数据源和DAO对象访问数据库。 JavaBeans实现模型,访问数据库,模型包括2个JavaBean:BookBean用于存放图书信息,BookDao类用于访问数据库。 Servlet实现控制器,控制器包括2个Servlet:BookQueryServlet3根据请求参数查询图书信息、BookInsertServlet用来向数据库中插入数据。 JSP页面实现视图。视图包括4个JSP
17、页面:bookQuery.jsp显示查询页面、bookInsert.jsp显示插入页面、display.jsp显示查询结果页面和errorPage.jsp显示错误页面。步骤1:创建存放图书信息的JavaBeans代码BookBean.java,它与任务1中的BookBean类相同。步骤2:创建下面的BookDao类,它是一个简单的JavaBeans,它实现数据库的访问。package com.dao;import java.sql.*;import javax.sql.*;import javax.naming.*;import com.demo.BookBean;public class B
18、ookDao private static InitialContext context= null; private DataSource dataSource = null; public BookDao() try if(context = null) context = new InitialContext(); dataSource = (DataSource)context.lookup(java:comp/env/jdbc/sampleDS); catch(NamingException e2) / 根据书号查询图书信息 public BookBean searchBook(St
19、ring bookid) Connection dbconn = null; PreparedStatement pstmt = null; ResultSet rst = null; BookBean book = new BookBean(); try dbconn = dataSource.getConnection(); pstmt = dbconn.prepareStatement(SELECT * FROM books WHERE bookid=?); pstmt.setString(1,bookid); rst = pstmt.executeQuery(); if(rst.nex
20、t() book.setBookid(rst.getString(bookid); book.setTitle(rst.getString(title); book.setAuthor(rst.getString(author); book.setPublisher(rst.getString(publisher); book.setPrice(rst.getDouble(price); return book; else return null; catch(SQLException se) return null; finally try dbconn.close(); catch(SQL
21、Exception se) / 插入一本图书记录 public boolean insertBook(BookBean book) Connection dbconn = null; PreparedStatement pstmt = null; try dbconn = dataSource.getConnection(); pstmt = dbconn.prepareStatement( INSERT INTO books VALUES(?,?,?,?,?); pstmt.setString(1,book.getBookid(); pstmt.setString(2,book.getTit
22、le(); pstmt.setString(3,book.getAuthor(); pstmt.setString(4,book.getPublisher(); pstmt.setDouble(5,book.getPrice(); pstmt.executeUpdate(); pstmt.close(); return true; catch(SQLException se) return false; finally try dbconn.close(); catch(SQLException se) 步骤3:bookQuery.jsp仍使用任务1的页面,但要将表单的action属性值修改为
23、“BooKQueryServlet3”。步骤4:下面的JSP页面bookInsert.jsp实现向数据库中插入数据 Book Insert请输入图书信息: 书号 书名 作者 出版社 单价 步骤5:显示查询结果的JSP页面displayBook.jsp和错误页面error.jsp与任务1相同。步骤6:下面的BookQueryServlet3实现从请求参数获得书号,然后从数据库中查找该书,最后根据查询结果将请求转发到显示页面(displayBook.jsp)或错误页面(error.jsp)。package com.demo;import java.io.*;import javax.servlet
24、.*;import javax.servlet.http.*;import com.demo.BookBean;import com.dao.BookDao;import javax.servlet.annotation.WebServlet;WebServlet(/BookQueryServlet3)public class BookQueryServlet3 extends HttpServlet public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletExcepti
25、on,IOException String bookid = request.getParameter(bookid); BookDao bookdao = new BookDao(); BookBean book = bookdao.searchBook(bookid); if(book!=null) request.getSession().setAttribute(book, book); response.sendRedirect(/helloweb/displayBook.jsp); else response.sendRedirect(/helloweb/errorPage.jsp
26、); 步骤8:下面的BookInsertServlet实现向数据库插入数据,并将控制请求的转发到bookInsert.jsp页面。package com.demo;import java.io.*;import javax.servlet.*;import javax.servlet.http.*;import com.demo.BookBean;import com.dao.BookDao;import javax.servlet.annotation.WebServlet;WebServlet(/BookInsertServlet)public class BookInsertServle
27、t extends HttpServlet public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException String message = null; BookBean book = new BookBean( request.getParameter(bookid),request.getParameter(title), request.getParameter(author),request.getParameter(publi
28、sher), Float.parseFloat(request.getParameter(price) ); BookDao bookdao = new BookDao(); boolean success = bookdao.insertBook(book); if(success) message = 成功插入一条记录!; else message = 插入记录错误!; request.setAttribute(result,message); RequestDispatcher view = request.getRequestDispatcher(/bookInsert.jsp); view.forward(request, response); 步骤9:先运行insertBook.jsp插入一本书信息,如书号:111书名:Java Web编程技术作者:沈泽刚出版社:清华大学出版社单价:39.00运行queryBook.jsp页面,查询书号为111的图书信息,看输出汉字是否乱码?如何解决。三 思考题1. 简述使用数据源访问数据库一般步骤。2. 简述使用数据源访问数据库比使用传统方法的优点。