一、实验目的
1.了解JDBC的结构体系; 2.掌握JDBC连接数据库的过程; 3.熟悉JDBC常用的API和类; 4.掌握通过JDBC向数据库:添加数据、查询数据、修改数据以及删除数据。
二、实验准备
JDBC是Java程序操作数据库的API,也是Java程序与数据库相交互的一门技术。JDBC是Java操作数据库的规范,由一组用Java语言编写的类和接口组成,它对数据库的操作提供了基本方法,但是对于数据库的细节操作由数据厂商提供数据库的驱动程序。
JDBC连接数据库的过程是:1.注册数据库驱动;2.构建数据库连接URL;3.获取Connection对象。
JDBC常用的API和类有:Connection接口、DriveManager类、Statement接口、PreparedStatement接口以及ResultSet接口。
Connection接口用于创建数据库的连接对象;DriveManager类主要作用与用户和驱动程序之间,并创建应用程序与数据库之间的连接;Statement接口提供了执行语句和获取查询结果的基本方法;PreparedStatement接口继承于Statement接口,它拥有Statement接口中的方法,而且应用于PreparedStatement接口中的SQL语句,可以使用占位符“?”来代替SQL语句中的参数,然后再对其进行赋值;ResultSet接口用于接收查询结果集。
因为我使用的编辑器是idea,与实验准备中的netbeans操作略有不同,就不按照实验准备中的进行配置了。
三、实验内容与步骤
1.创建一个Java Web项目,通过JDBC实现图书信息添加功能
右击新建项目下的库,选择“添加JAR/文件件”,如下图所示。 选择数据库驱动程序 jtds-1.2.jar 我这里使用的是idea
(1)在SQL server 2005中新建查询,建立一个数据库bookstore和表books,查询如下:
create database bookstore
GO
use bookstore
GO
CREATE TABLE books (
id integer not null,
name varchar(45) null,
price float null,
bookCount int null,
author varchar(45) null
);
(2)在Java Web项目中创建一个名称为Book的JavaBeans类(右击项目新建一个Java类),用于保存图书信息,源代码如下:
package com.demo;
public class Book {
private int id;
private String name;
private float price;
private int bookCount;
private String author;
public int getId(){
return this.id;
}
public void setId(int id){
this.id = id;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name= name;
}
public float getPrice(){
return this.price;
}
public void setPrice(float price){
this.price = price;
}
public int getBookCount(){
return this.bookCount;
}
public void setBookCount(int bookCount){
this.bookCount = bookCount;
}
public String getAuthor(){
return this.author;
}
public void setAuthor(String author){
this.author = author;
}
}
(3)新建一个index.jsp,源代码如下:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>添加图书信息</title>
</head>
<body>
<form action="AddBook.jsp" method="post" onsubmit =" return check(this);">
<table align ="center" width ="450">
<tr>
<td align ="center" colspan="2">
<h2>添加图书信息</h2>
<hr>
</td>
</tr>
<tr>
<td align ="right">
图书名称:
</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td align ="right">
价格:
</td>
<td><input type="text" name="price"></td>
</tr>
<tr>
<td align ="right">
数量:
</td>
<td><input type="text" name="bookCount"></td>
</tr>
<tr>
<td align ="right">
作者:
</td>
<td><input type="text" name="author"></td>
</tr>
<tr>
<td align ="center" colspan="2">
<input type="submit" value="添加">
</td>
</tr>
</table>
</form>
</body>
</html>
(4)新建一个AddBook.jsp,用于连接数据库并进行添加数据,源代码如下:
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%request.setCharacterEncoding("UTF-8");%>
<jsp:useBean id="book" class="com.demo.Book"></jsp:useBean>
<jsp:setProperty property="*" name="book"></jsp:setProperty>
<%
try{
//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// String url = "jdbc:sqlserver://localhost:1433;databaseName = bookstore";
// String username = "sa";
// String password = "sa";
//加载驱动程序
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
String url="jdbc:jtds:sqlserver://localhost:1433/bookstore ";
String username="sa";
String password="123";
Connection conn = DriverManager.getConnection(url,username,password);
String sql = "insert into books(name,price,bookCount,author)values(?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,book.getName());
ps.setFloat(2,book.getPrice());
ps.setInt(3,book.getBookCount());
ps.setString(4,book.getAuthor());
int row = ps.executeUpdate();
if(row>0){
out.println("成功添加了"+row+"条数据");
}
ps.close();
conn.close();
}catch (Exception e){
out.println("图书信息添加失败");
e.printStackTrace();
}
%>
<br>
<a href="index.jsp">返回</a>
</body>
</html>
(5)运行index.jsp,为数据库添加数据 图3-3 新建Book.Java、addbook.jsp、index.jsp
图3-4 添加图书信息
图3-5 成功添加数据
图3-6 在数据库查看插入的数据
2.通过JDBC对数据库bookstores的表格books进行数据查询
(1)打开SQL server 2005,对数据库bookstores的表格books添加数据 图3-7 直接添加数据
(2)创建名称为FindServlet的servlet对象,源代码如下:
package com.demo;
import java.beans.Statement;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "FindServlet", urlPatterns = {"/FindServlet"})
public class FindServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
response.setContentType("text/html;charset=UTF-8");
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
String url="jdbc:jtds:sqlserver://localhost:1433/bookstore ";
String username="sa";
String password="123";
Connection conn = DriverManager.getConnection(url,username,password);
java.sql.Statement stmt = conn.createStatement();
String sql = "select * from books";
ResultSet rs = stmt.executeQuery(sql);
List<Book> list = new ArrayList<Book>();
while(rs.next()){
Book book = new Book();
book.setId(rs.getInt("id"));
book.setName(rs.getString("name"));
book.setPrice(rs.getFloat("price"));
book.setBookCount(rs.getInt("bookCount"));
book.setAuthor(rs.getString("author"));
list.add(book);
}
request.setAttribute("list", list);
rs.close();
stmt.close();
conn.close();
PrintWriter out = response.getWriter();
}catch (ClassNotFoundException e){
e.printStackTrace();
PrintWriter out = response.getWriter();
out.println("查询失败1");
}catch (SQLException e){
e.printStackTrace();
PrintWriter out = response.getWriter();
out.println("查询失败2");
}
request.getRequestDispatcher("book_list.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
(3)新建一个book_list.jsp,用于显示所有图书信息,源代码如下:
<%@page import="com.demo.Book"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>查询图书信息</title>
</head>
<body>
<table align="center" width="600" border="1">
<tr>
<td align="center" width="600" colspan="5">
<h2>所有图书信息</h2>
</td>
</tr>
<tr align="center" >
<td><b>ID</b></td>
<td><b>图书名称</b></td>
<td><b>价格</b></td>
<td><b>数量</b></td>
<td><b>作者</b></td>
</tr>
<%
List<Book> list=(List<Book>)request.getAttribute("list");
if(list==null||list.size()<1){
out.println("没有任何数据");
}else{
for(Book book:list){
%>
<tr align="center">
<td><%=book.getId()%></td>
<td><%=book.getName()%></td>
<td><%=book.getPrice()%></td>
<td><%=book.getBookCount()%></td>
<td><%=book.getAuthor()%></td>
</tr>
<%
}
}
%>
</table>
</body>
</html>
(4)新建一个find.jsp,源代码如下:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>进行查询</title>
</head>
<body>
<a href="FindServlet">查看所有图书</a>
</body>
</html>
(5)运行find.jsp,显示查询数据库的结果
图3-8 新建 FindServlet、book_list.jsp、find.jsp
图3-9 显示查询结果
3.通过JDBC对数据库bookstores的表格books进行数据删除
(1)新建一个delete.jsp,用于显示数据并进行删除操作,源代码如下:
<%@page import="com.demo.Book"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>查询图书信息</title>
</head>
<body>
<table align="center" width="600" border="1">
<tr>
<td align="center" width="600" colspan="5">
<h2>所有图书信息</h2>
</td>
</tr>
<tr align="center" >
<td><b>ID</b></td>
<td><b>图书名称</b></td>
<td><b>价格</b></td>
<td><b>数量</b></td>
<td><b>作者</b></td>
<td><b>删除</b></td>
</tr>
<%
List<Book> list=(List<Book>)request.getAttribute("list");
if(list==null||list.size()<1){
out.println("没有任何数据");
}else{
for(Book book:list){
%>
<tr align="center">
<td><%=book.getId()%></td>
<td><%=book.getName()%></td>
<td><%=book.getPrice()%></td>
<td><%=book.getBookCount()%></td>
<td><%=book.getAuthor()%></td>
<td><a href="DeleteServlet?id=<%=book.getId()%>">删除</a>
</tr>
<%
}
}
%>
</table>
</body>
</html>
(2)创建一个名称为delete_Find的Servlet,用于查询数据,源代码如下:
package com.demo;
import java.beans.Statement;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "delete_Find", urlPatterns = {"/delete_Find"})
public class delete_Find extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
response.setContentType("text/html;charset=UTF-8");
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
String url="jdbc:jtds:sqlserver://localhost:1433/bookstore ";
String username="sa";
String password="123";
Connection conn = DriverManager.getConnection(url,username,password);
java.sql.Statement stmt = conn.createStatement();
String sql = "select * from books";
ResultSet rs = stmt.executeQuery(sql);
List<Book> list = new ArrayList<Book>();
while(rs.next()){
Book book = new Book();
book.setId(rs.getInt("id"));
book.setName(rs.getString("name"));
book.setPrice(rs.getFloat("price"));
book.setBookCount(rs.getInt("bookCount"));
book.setAuthor(rs.getString("author"));
list.add(book);
}
request.setAttribute("list", list);
rs.close();
stmt.close();
conn.close();
PrintWriter out = response.getWriter();
for(Book book:list){
out.println(book.getId());
out.println(book.getName());
out.println(book.getPrice());
out.println(book.getBookCount());
out.println(book.getAuthor()+"<br>");
}
}catch (ClassNotFoundException e){
e.printStackTrace();
PrintWriter out = response.getWriter();
out.println("查询失败1");
}catch (SQLException e){
e.printStackTrace();
PrintWriter out = response.getWriter();
out.println("查询失败2");
}
request.getRequestDispatcher("delete.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
(3)创建一个名称为DeleteServlet的Servlet,用于删除数据的处理,源代码如下:
package com.demo;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "DeleteServlet", urlPatterns = {"/DeleteServlet"})
public class DeleteServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.valueOf(request.getParameter("id"));
if(id==0){
request.getRequestDispatcher("book_list.jsp").forward(request, response);
}
try{
response.setContentType("text/html;charset=UTF-8");
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
String url="jdbc:jtds:sqlserver://localhost:1433/bookstore ";
String username="sa";
String password="123";
Connection conn = DriverManager.getConnection(url,username,password);
String sql = "delete from books where id=?";
PreparedStatement ps =conn.prepareStatement(sql);
ps.setInt(1,id);
PrintWriter out = response.getWriter();
int row = ps.executeUpdate();
if(row>0){
request.getRequestDispatcher("success.jsp").forward(request, response);
}
ps.close();
conn.close();
}catch (ClassNotFoundException e){
e.printStackTrace();
PrintWriter out = response.getWriter();
out.println("查询失败1");
}catch (SQLException e){
e.printStackTrace();
PrintWriter out = response.getWriter();
out.println("查询失败2");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
(4)新建一个success.jsp,用于显示是否删除成功的信息,源代码如下:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
成功删除记录!
</body>
</html>
(5)新建一个delete_first.jsp,源代码如下:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>进行查询</title>
</head>
<body>
<a href="delete_Find">查看所有图书</a>
</body>
</html>
(6)运行delete_first.jsp,显示删除数据的结果 图3-10 新建DeleteServlet、delete_Find、delete.jsp、delete.jsp、success.jsp
图3-11 delete_first.jsp
图3-12 选择进行删除的数据
图3-13 成功删除第一条数据
图8-10 查看数据库,显示第一条数据已经被删除
四、实验思考总结
本次实验,是我第一次完整的接触javaweb项目,在未接触前觉得javaweb有些许的复杂,可能要很难懂,通过老师上课简述的一些知识,结合老师给的代码,再加上课下自己翻阅书籍和视频学到的,对javaweb有一个入门级别的了解(java类、servlet程序、jsp文件),可以正确的运行代码对于我来说是最大的收获。
在实验过程中,如何让代码运行是卡壳时间最久的问题,一是软件问题,netbeans和idea虽然都属于java ide,但是在语法和描述上略有区别,在导入jar包时,在netbeans中可以直接通过添加外部库导入,而在idea中则需要放在webapp的lib目录下。二是代码问题,因为版本和环境的问题,有些代码在高版本idea中已经被替代或者过时,需要找新版本中的函数或者命令去替换。同时在实验中也了解了tomcat是作为一个容器,搭载在web框架的最底层的作为配置。 最后放一下项目的最终文件目录
|