JEE_JDBC1

JDBC是Java程序与数据库系统通信的标准API,定义在JDK的API中,通过JDBC技术,Java程序可以很方便地与各种数据库进行交互,JDBC在Java程序与数据库系统之间建立了一座桥梁。

 

JDBC API:

Connection接口.

DriverManager类.

Statement接口.

PreparedStatement接口.

ResultSet接口.

 

JDBC连接数据库的过程:

1.注册数据库驱动:

2.构建数据库连接URL:

3.获取Connection对象

(JSP连接MySQL:先启动MySQL,创建Web项目及导包)

 

例:通过JDBC连接MySQL数据库:

index.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@page import="java.sql.Connection"%>
<%@page import="java.sql.SQLException"%>
<%@page import="java.sql.DriverManager"%>

<%@page import="java.util.Enumeration"%><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>连接MySQL数据库</title>
</head>
<body>
<%
    try {
        // 加载数据库驱动,注册到驱动管理器
        Class.forName("com.mysql.jdbc.Driver");
        // 数据库连接字符串
        String url = "jdbc:mysql://localhost:3306/mysql";
        // 数据库用户名
        String username = "root";
        // 数据库密码
        String password = "111";
        // 创建Connection连接
        Connection conn = DriverManager.getConnection(url,username,password);
        // 判断 数据库连接是否为空
        if(conn != null){
            // 输出连接信息
            out.println("数据库连接成功!");
            // 关闭数据库连接
            conn.close();
        }else{
            // 输出连接信息
            out.println("数据库连接失败!");
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }
%>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>11.1</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

JDBC操作MySQL数据库:

1.添加数据:

Book.java
//JavaBean

package com.lyq.bean;
/**
 * 图书实体类
 * @author Li YongQiang
 */
public class Book {
    // 编号
    private int id;
    // 图书名称
    private String name;
    // 价格
    private double price;
    // 数量
    private int bookCount;
    // 作者
    private String author;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public int getBookCount() {
        return bookCount;
    }
    public void setBookCount(int bookCount) {
        this.bookCount = bookCount;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
}
index.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>添加图书信息</title>
<script type="text/javascript">
    function check(form){
        with(form){
            if(name.value == ""){
                alert("图书名称不能为空");
                return false;
            }
            if(price.value == ""){
                alert("价格不能为空");
                return false;
            }
            if(author.value == ""){
                alert("作者不能为空");
                return false;
            }
            return true;
        }
    }
</script>
</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>
AddBook.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@page import="java.sql.Connection"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.PreparedStatement"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>添加结果</title>
</head>
<body>
    <%request.setCharacterEncoding("GB18030"); %>
    <jsp:useBean id="book" class="com.lyq.bean.Book"></jsp:useBean>
    <jsp:setProperty property="*" name="book"/>
    <%
        try {
            // 加载数据库驱动,注册到驱动管理器
            Class.forName("com.mysql.jdbc.Driver");
            // 数据库连接字符串
            String url = "jdbc:mysql://localhost:3306/db_database11";
            // 数据库用户名
            String username = "root";
            // 数据库密码
            String password = "111";
            // 创建Connection连接
            Connection conn = DriverManager.getConnection(url,username,password);
            // 添加图书信息的SQL语句
            String sql = "insert into tb_book(name,price,bookCount,author) values(?,?,?,?)";
            // 获取PreparedStatement
            PreparedStatement ps = conn.prepareStatement(sql);
            // 对SQL语句中的第1个参数赋值
            ps.setString(1, book.getName());
            // 对SQL语句中的第2个参数赋值
            ps.setDouble(2, book.getPrice());
            // 对SQL语句中的第3个参数赋值
            ps.setInt(3,book.getBookCount());
            // 对SQL语句中的第4个参数赋值
            ps.setString(4, book.getAuthor());
            // 执行更新操作,返回所影响的行数
            int row = ps.executeUpdate();
            // 判断是否更新成功
            if(row > 0){
                // 更新成输出信息
                out.print("成功添加了 " + row + "条数据!");
            }
            // 关闭PreparedStatement,释放资源
            ps.close();
            // 关闭Connection,释放资源
            conn.close();
        } catch (Exception e) {
            out.print("图书信息添加失败!");
            e.printStackTrace();
        }
    %>
    <br>
    <a href="index.jsp">返回</a>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>11.2</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

2.查询数据: ResultSet集合所查询的数据是位于集合的中间位置,在第一条数据之前与最后一条数据之后都还有一个位置,

默认情况下ResultSet的光标位置在第一行数据之前,所以在第一次获取数据时就需要移动光标的位置。

由于这个位置关系,使用Java之中的for循环,do...while循环等都不能对其很好地进行遍历,此处可以用 "while(rs.next())" 来遍历.

通过光标定位到查询结果中的指定行后,通过ResultSet对象提供的一系列getXxx()方法就可获取当前行的数据.

index.jsp---FindServlet.java---book_list.jsp.(JavaBean,web.xml)

Book.java
package com.lyq.bean;
/**
 * 图书实体类
 * @author Li YongQiang
 */
public class Book {
    // 编号
    private int id;
    // 图书名称
    private String name;
    // 价格
    private double price;
    // 数量
    private int bookCount;
    // 作者
    private String author;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public int getBookCount() {
        return bookCount;
    }
    public void setBookCount(int bookCount) {
        this.bookCount = bookCount;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
}
FindServlet .java
package com.lyq.bean;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 查询图书信息的Servlet对象
 * @author Li YongQiang
 *
 */
public class FindServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            // 加载数据库驱动,注册到驱动管理器
            Class.forName("com.mysql.jdbc.Driver");
            // 数据库连接字符串
            String url = "jdbc:mysql://localhost:3306/db_database11";
            // 数据库用户名
            String username = "root";
            // 数据库密码
            String password = "111";
            // 创建Connection连接
            Connection conn = DriverManager.getConnection(url,username,password);
            // 获取Statement
            Statement stmt = conn.createStatement();
            // 添加图书信息的SQL语句
            String sql = "select * from tb_book";
            // 执行查询
            ResultSet rs = stmt.executeQuery(sql);
            // 实例化List对象
            List<Book> list = new ArrayList<Book>();
            // 判断光标向后移动,并判断是否有效
            while(rs.next()){
                // 实例化Book对象
                Book book = new Book();
                // 对id属性赋值
                book.setId(rs.getInt("id"));
                // 对name属性赋值
                book.setName(rs.getString("name"));
                // 对price属性赋值
                book.setPrice(rs.getDouble("price"));
                // 对bookCount属性赋值
                book.setBookCount(rs.getInt("bookCount"));
                // 对author属性赋值
                book.setAuthor(rs.getString("author"));
                // 将图书对象添加到集合中
                list.add(book);
            }
            // 将图书集合放置到request之中
            request.setAttribute("list", list);
            rs.close();        // 关闭ResultSet
            stmt.close();    // 关闭Statement
            conn.close();    // 关闭Connection
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 请求转发到book_list.jsp
        request.getRequestDispatcher("book_list.jsp").forward(request, response);
    }
}
book_list.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@page import="java.util.List"%>
<%@page import="com.lyq.bean.Book"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>所有图书信息</title>
<style type="text/css">
    td{font-size: 12px;}
    h2{margin: 0px}
</style>
</head>
<body>
    <table align="center" width="450" border="1" height="180" bordercolor="white" bgcolor="black" cellpadding="1" cellspacing="1">
        <tr bgcolor="white">
            <td align="center" colspan="5">
                <h2>所有图书信息</h2>
            </td>
        </tr>
        <tr align="center" bgcolor="#e1ffc1" >
            <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.print("没有数据!");
                    }else{
                        // 遍历图书集合中的数据
                        for(Book book : list){
            %>
                <tr align="center" bgcolor="white">
                    <td><%=book.getId()%></td>
                    <td><%=book.getName()%></td>
                    <td><%=book.getPrice()%></td>
                    <td><%=book.getBookCount()%></td>
                    <td><%=book.getAuthor()%></td>
                </tr>
            <%
                    }
                }
            %>
    </table>
</body>
</html>
index.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>查看所有图书</title>
</head>
<body>
    <a href="FindServlet">查看所有图书</a>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>11.3</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>FindServlet</display-name>
    <servlet-name>FindServlet</servlet-name>
    <servlet-class>com.lyq.bean.FindServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>FindServlet</servlet-name>
    <url-pattern>/FindServlet</url-pattern>
  </servlet-mapping>
</web-app>

 

3.修改数据

由于SQL语句中要传递参数,修改数据应该使用PreparedStatement对象进行操作.

index.jsp---FindServlet.java---book_list.jsp---UpdateServlet.java---FindServlet.java---book_list.jsp.(JavaBean,web.xml)

index.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>查看所有图书</title>
</head>
<body>
    <a href="FindServlet">查看所有图书</a>
</body>
</html>
FindServlet.java
package com.lyq.bean;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 查询图书信息的Servlet对象
 * @author Li YongQiang
 *
 */
public class FindServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            // 加载数据库驱动,注册到驱动管理器
            Class.forName("com.mysql.jdbc.Driver");
            // 数据库连接字符串
            String url = "jdbc:mysql://localhost:3306/db_database11";
            // 数据库用户名
            String username = "root";
            // 数据库密码
            String password = "111";
            // 创建Connection连接
            Connection conn = DriverManager.getConnection(url,username,password);
            // 获取Statement
            Statement stmt = conn.createStatement();
            // 添加图书信息的SQL语句
            String sql = "select * from tb_book";
            // 执行查询
            ResultSet rs = stmt.executeQuery(sql);
            // 实例化List对象
            List<Book> list = new ArrayList<Book>();
            // 判断光标向后移动,并判断是否有效
            while(rs.next()){
                // 实例化Book对象
                Book book = new Book();
                // 对id属性赋值
                book.setId(rs.getInt("id"));
                // 对name属性赋值
                book.setName(rs.getString("name"));
                // 对price属性赋值
                book.setPrice(rs.getDouble("price"));
                // 对bookCount属性赋值
                book.setBookCount(rs.getInt("bookCount"));
                // 对author属性赋值
                book.setAuthor(rs.getString("author"));
                // 将图书对象添加到集合中
                list.add(book);
            }
            // 将图书集合放置到request之中
            request.setAttribute("list", list);
            rs.close();        // 关闭ResultSet
            stmt.close();    // 关闭Statement
            conn.close();    // 关闭Connection
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 请求转发到book_list.jsp
        request.getRequestDispatcher("book_list.jsp").forward(request, response);
    }
}
book_list.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@page import="java.util.List"%>
<%@page import="com.lyq.bean.Book"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>所有图书信息</title>
<style type="text/css">
    form{margin: 0px;}
    td{font-size: 12px;}
    h2{margin: 2px}
</style>
<script type="text/javascript">
    function check(form){
        with(form){
            if(bookCount.value == ""){
                alert("请输入更新数量!");
                return false;
            }
            if(isNaN(bookCount.value)){
                alert("格式错误!");
                return false;
            }
            return true;;
        }
    }
</script>
</head>
<body>
    <table align="center" width="500" border="1" height="170" bordercolor="white" bgcolor="black" cellpadding="1" cellspacing="1">
        <tr bgcolor="white">
            <td align="center" colspan="6">
                <h2>所有图书信息</h2>
            </td>
        </tr>
        <tr align="center" bgcolor="#e1ffc1" >
            <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.print("没有数据!");
                    }else{
                        // 遍历图书集合中的数据
                        for(Book book : list){
            %>
                <tr align="center" bgcolor="white">
                    <td><%=book.getId()%></td>
                    <td><%=book.getName()%></td>
                    <td><%=book.getPrice()%></td>
                    <td><%=book.getBookCount()%></td>
                    <td><%=book.getAuthor()%></td>
                    <td>
                        <form action="UpdateServlet" method="post" onsubmit="return check(this);">
                            <input type="hidden" name="id" value="<%=book.getId()%>">
                            <input type="text" name="bookCount" size="3">
                            <input type="submit" value="修 改">
                        </form>
                    </td>
                </tr>
            <%

                    }
                }
            %>
    </table>
</body>
</html>
UpdateServlet.java
package com.lyq.bean;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class UpdateServlet
 */
public class UpdateServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.valueOf(request.getParameter("id"));
        int bookCount = Integer.valueOf(request.getParameter("bookCount")); 
        try {
            // 加载数据库驱动,注册到驱动管理器
            Class.forName("com.mysql.jdbc.Driver");
            // 数据库连接字符串
            String url = "jdbc:mysql://localhost:3306/db_database11";
            // 数据库用户名
            String username = "root";
            // 数据库密码
            String password = "111";
            // 创建Connection连接
            Connection conn = DriverManager.getConnection(url,username,password);
            // 更新SQL语句
            String sql = "update tb_book set bookcount=? where id=?";
            // 获取PreparedStatement
            PreparedStatement ps = conn.prepareStatement(sql);
            // 对SQL语句中的第一个参数赋值
            ps.setInt(1, bookCount);
            // 对SQL语句中的第二个参数赋值
            ps.setInt(2, id);
            // 执行更新操作
            ps.executeUpdate();
            // 关闭PreparedStatement
            ps.close();
            // 关闭Connection
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        } 
        // 重定向到FindServlet
        response.sendRedirect("FindServlet");
    }

}
Book.java
package com.lyq.bean;
/**
 * 图书实体类
 * @author Li YongQiang
 */
public class Book {
    // 编号
    private int id;
    // 图书名称
    private String name;
    // 价格
    private double price;
    // 数量
    private int bookCount;
    // 作者
    private String author;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public int getBookCount() {
        return bookCount;
    }
    public void setBookCount(int bookCount) {
        this.bookCount = bookCount;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>11.4</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <display-name>UpdateServlet</display-name>
    <servlet-name>UpdateServlet</servlet-name>
    <servlet-class>com.lyq.bean.UpdateServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UpdateServlet</servlet-name>
    <url-pattern>/UpdateServlet</url-pattern>
  </servlet-mapping>
   <servlet>
    <display-name>FindServlet</display-name>
    <servlet-name>FindServlet</servlet-name>
    <servlet-class>com.lyq.bean.FindServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>FindServlet</servlet-name>
    <url-pattern>/FindServlet</url-pattern>
  </servlet-mapping>
</web-app>

 

4.删除数据

book_list.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@page import="java.util.List"%>
<%@page import="com.lyq.bean.Book"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>所有图书信息</title>
<style type="text/css">
    form{margin: 0px;}
    td{font-size: 12px;}
    h2{margin: 2px}
</style>
<script type="text/javascript">
    function check(form){
        with(form){
            if(bookCount.value == ""){
                alert("请输入更新数量!");
                return false;
            }
            if(isNaN(bookCount.value)){
                alert("格式错误!");
                return false;
            }
            return true;;
        }
    }
</script>
</head>
<body>
    <table align="center" width="450" border="1" height="170" bordercolor="white" bgcolor="black" cellpadding="1" cellspacing="1">
        <tr bgcolor="white">
            <td align="center" colspan="6">
                <h2>所有图书信息</h2>
            </td>
        </tr>
        <tr align="center" bgcolor="#e1ffc1" >
            <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.print("没有数据!");
                    }else{
                        // 遍历图书集合中的数据
                        for(Book book : list){
            %>
                <tr align="center" bgcolor="white">
                    <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>
                    </td>
                </tr>
            <%
                    }
                }
            %>
    </table>
</body>
</html>
DeleteServlet.java
package com.lyq.bean;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DeleteServlet
 */
public class DeleteServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取图书id
        int id = Integer.valueOf(request.getParameter("id"));
        try {
            // 加载数据库驱动,注册到驱动管理器
            Class.forName("com.mysql.jdbc.Driver");
            // 数据库连接字符串
            String url = "jdbc:mysql://localhost:3306/db_database11";
            // 数据库用户名
            String username = "root";
            // 数据库密码
            String password = "111";
            // 创建Connection连接
            Connection conn = DriverManager.getConnection(url,username,password);
            // 删除图书信息的SQL语句
            String sql = "delete from tb_book where id=?";
            // 获取PreparedStatement
            PreparedStatement ps = conn.prepareStatement(sql);
            // 对SQL语句中的第一个占位符赋值
            ps.setInt(1, id);
            // 执行更新操作
            ps.executeUpdate();
            // 关闭PreparedStatement
            ps.close();
            // 关闭Connection
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        } 
        // 重定向到FindServlet
        response.sendRedirect("FindServlet");
    }
}

 

5.批处理

PreparedStatement对象的批处理操作,单条数据提交用.addBatch(),批处理提交是用.executeBatch(),而不是executeUpdate(),executeQuery().

另外,JavaBean对象的使用包括<jsp:useBean>实例化对象,或者直接创建用其public class创建类对象.

JavaBean对象的操作包括<jsp:setProperty>,<jsp:getProperty>,还可以直接调用其中定义的方法函数(saveBatch).

Batch.java
package com.lyq;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Random;
/**
 * 批处理
 * @author Li YongQiang
 */
public class Batch {
    /**
     * 获取数据库连接
     * @return Connection对象
     */
    public Connection getConnection(){
        // 数据库连接
        Connection conn = null;
        try {
            // 加载数据库驱动,注册到驱动管理器
            Class.forName("com.mysql.jdbc.Driver");
            // 数据库连接字符串
            String url = "jdbc:mysql://localhost:3306/db_database11";
            // 数据库用户名
            String username = "root";
            // 数据库密码
            String password = "111";
            // 创建Connection连接
            conn = DriverManager.getConnection(url,username,password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 返回数据库连接
        return conn;
    }
    /**
     * 批量添加数据
     * @return 所影响的行数
     */
    public int saveBatch(){
        // 行数
        int row = 0 ;
        // 获取数据库连接
        Connection conn = getConnection();
        try {
            // 插入数据的SQL语句
            String sql = "insert into tb_student_batch(id,name,sex,age) values(?,?,?,?)";
            // 创建PreparedStatement
            PreparedStatement ps = conn.prepareStatement(sql);
            // 实例化Random
            Random random = new Random();
            // 循环添加数据
            for (int i = 0; i < 10; i++) {
                // 对SQL语句中的第1个参数赋值
                ps.setInt(1, i+1);
                // 对SQL语句中的第2个参数赋值
                ps.setString(2, "学生" + i);
                // 对SQL语句中的第3个参数赋值
                ps.setBoolean(3, i % 2 == 0 ? true : false);
                // 对SQL语句中的第4个参数赋值
                ps.setInt(4, random.nextInt(5) + 10);
                // 添加批处理命令
                ps.addBatch();
            }
            // 执行批处理操作并返回计数组成的数组
            int[] rows = ps.executeBatch();
            // 对行数赋值
            row = rows.length;
            // 关闭PreparedStatement
            ps.close();
            // 关闭Connection
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 返回添加的行数
        return row;
    }
}
index.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>首页</title>
</head>
<body>
    <jsp:useBean id="batch" class="com.lyq.Batch"></jsp:useBean>
    <%
        // 执行批量插入操作
        int row = batch.saveBatch();
        out.print("批量插入了【" + row + "】条数据!");
    %>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>11.6</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

6.存储过程

index.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@page import="java.util.List"%>
<%@page import="com.lyq.bean.Book"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>所有图书信息</title>
<style type="text/css">
    td{font-size: 12px;}
    h2{margin: 0px}
</style>
</head>
<body>
    <jsp:useBean id="findBook" class="com.lyq.bean.FindBook"></jsp:useBean>
    <table align="center" width="450" border="1" height="180" bordercolor="white" bgcolor="black" cellpadding="1" cellspacing="1">
        <tr bgcolor="white">
            <td align="center" colspan="5">
                <h2>所有图书信息</h2>
            </td>
        </tr>
        <tr align="center" bgcolor="#e1ffc1" >
            <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 = findBook.findAll();
                    // 判断集合是否有效
                    if(list == null || list.size() < 1){
                        out.print("没有数据!");
                    }else{
                        // 遍历图书集合中的数据
                        for(Book book : list){
            %>
                <tr align="center" bgcolor="white">
                    <td><%=book.getId()%></td>
                    <td><%=book.getName()%></td>
                    <td><%=book.getPrice()%></td>
                    <td><%=book.getBookCount()%></td>
                    <td><%=book.getAuthor()%></td>
                </tr>
            <%
                    }
                }
            %>
    </table>
</body>
</html>
FindBook.java
package com.lyq.bean;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 查询图书信息
 * @author Li YongQiang
 *
 */
public class FindBook {
    /**
     * 获取数据库连接
     * @return Connection对象
     */
    public Connection getConnection(){
        // 数据库连接
        Connection conn = null;
        try {
            // 加载数据库驱动,注册到驱动管理器
            Class.forName("com.mysql.jdbc.Driver");
            // 数据库连接字符串
            String url = "jdbc:mysql://localhost:3306/db_database11";
            // 数据库用户名
            String username = "root";
            // 数据库密码
            String password = "111";
            // 创建Connection连接
            conn = DriverManager.getConnection(url,username,password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 返回数据库连接
        return conn;
    }
    /**
     * 通过存储过程查询数据
     * @return  List<Book> 
     */
    public List<Book> findAll(){
        // 实例化List对象
        List<Book> list = new ArrayList<Book>();
        // 创建数据库连接
        Connection conn = getConnection();
        try {
            //调用存储过程
            CallableStatement cs = conn.prepareCall("{call findAllBook()}");
            // 执行查询操作,并获取结果集
            ResultSet rs = cs.executeQuery();
            // 判断光标向后移动,并判断是否有效
            while(rs.next()){
                // 实例化Book对象
                Book book = new Book();
                // 对id属性赋值
                book.setId(rs.getInt("id"));
                // 对name属性赋值
                book.setName(rs.getString("name"));
                // 对price属性赋值
                book.setPrice(rs.getDouble("price"));
                // 对bookCount属性赋值
                book.setBookCount(rs.getInt("bookCount"));
                // 对author属性赋值
                book.setAuthor(rs.getString("author"));
                // 将图书对象添加到集合中
                list.add(book);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 返回list
        return list;
    }
}
Book.java
package com.lyq.bean;
/**
 * 图书实体类
 * @author Li YongQiang
 */
public class Book {
    // 编号
    private int id;
    // 图书名称
    private String name;
    // 价格
    private double price;
    // 数量
    private int bookCount;
    // 作者
    private String author;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public int getBookCount() {
        return bookCount;
    }
    public void setBookCount(int bookCount) {
        this.bookCount = bookCount;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>11.7</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

 

例:MySQL分页查询

Product.java
package com.lyq.bean;

/**
 * 商品
 * @author Li YongQiang
 *
 */
public class Product {
    public static final int PAGE_SIZE = 2;
    // 编号
    private int id;
    // 名称
    private String name;
    // 价格
    private double price;
    // 数量
    private int num;
    // 单位
    private String unit;
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public String getUnit() {
        return unit;
    }
    public void setUnit(String unit) {
        this.unit = unit;
    }
}
BookDao.java
package com.lyq.bean;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * 商品数据库操作
 * @author Li YongQiang
 *
 */

public class BookDao {
    /**
     * 获取数据库连接
     * @return Connection对象
     */
    public Connection getConnection(){
        // 数据库连接
        Connection conn = null;
        try {
            // 加载数据库驱动,注册到驱动管理器
            Class.forName("com.mysql.jdbc.Driver");
            // 数据库连接字符串
            String url = "jdbc:mysql://localhost:3306/db_database11";
            // 数据库用户名
            String username = "root";
            // 数据库密码
            String password = "111";
            // 创建Connection连接
            conn = DriverManager.getConnection(url,username,password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 返回数据库连接
        return conn;
    }
    
    /**
     * 分页查询所有商品信息
     * @param page 页数
     * @return List<Product>
     */
    public List<Product> find(int page){
        // 创建List
        List<Product> list = new ArrayList<Product>();
        // 获取数据库连接
        Connection conn = getConnection();
        // 分页查询的SQL语句
        String sql = "select * from tb_product order by id desc limit ?,?";
        try {
            // 获取PreparedStatement
            PreparedStatement ps = conn.prepareStatement(sql);
            // 对SQL语句中的第1个参数赋值
            ps.setInt(1, (page - 1) * Product.PAGE_SIZE);
            // 对SQL语句中的第2个参数赋值
            ps.setInt(2, Product.PAGE_SIZE);
            // 执行查询操作
            ResultSet rs = ps.executeQuery();
            // 光标向后移动,并判断是否有效
            while(rs.next()){
                // 实例化Product
                Product p = new Product();
                // 对id属性赋值
                p.setId(rs.getInt("id"));
                // 对name属性赋值
                p.setName(rs.getString("name"));
                // 对num属性赋值
                p.setNum(rs.getInt("num"));
                // 对price属性赋值
                p.setPrice(rs.getDouble("price"));
                // 对unit属性赋值
                p.setUnit(rs.getString("unit"));
                // 将Product添加到List集合中
                list.add(p);
            }
            // 关闭ResultSet
            rs.close();
            // 关闭PreparedStatement
            ps.close();
            // 关闭Connection
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
    
    /**
     * 查询总记录数
     * @return 总记录数
     */
    public int findCount(){
        // 总记录数
        int count = 0;
        // 获取数据库连接
        Connection conn = getConnection();
        // 查询总记录数SQL语句
        String sql = "select count(*) from tb_product";
        try {
            // 创建Statement
            Statement stmt = conn.createStatement();
            // 查询并获取ResultSet
            ResultSet rs = stmt.executeQuery(sql);
            // 光标向后移动,并判断是否有效
            if(rs.next()){
                // 对总记录数赋值
                count = rs.getInt(1);
            }
            // 关闭ResultSet
            rs.close();
            // 关闭Connection
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 返回总记录数
        return count;
    }
}
FindServlet。java
package com.lyq.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lyq.bean.Product;
import com.lyq.bean.BookDao;

/**
 * Servlet implementation class FindServlet
 */
public class FindServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 当前页码
        int currPage = 1;
        // 判断传递页码是否有效
        if(request.getParameter("page") != null){   
            // 对当前页码赋值
            currPage = Integer.parseInt(request.getParameter("page"));   //page--------
        }
        // 实例化ProductDao
        BookDao dao = new BookDao();
        // 查询所有商品信息
        List<Product> list = dao.find(currPage);
        // 将list放置到request之中
        request.setAttribute("list", list);
        // 总页数
        int pages ;
        // 查询总记录数
        int count = dao.findCount();   //------------------
        // 计算总页数
        if(count % Product.PAGE_SIZE == 0){
            // 对总页数赋值
            pages = count / Product.PAGE_SIZE;
        }else{
            // 对总页数赋值
            pages = count / Product.PAGE_SIZE + 1;
        }
        // 实例化StringBuffer
        StringBuffer sb = new StringBuffer();
        // 通过循环构建分页条
        for(int i=1; i <= pages; i++){
            // 判断是否为当前页
            if(i == currPage){
                // 构建分页条
                sb.append("『" + i + "』");
            }else{
                // 构建分页条
                sb.append("<a href='FindServlet?page=" + i + "'>" + i + "</a>");  //参数page--------
            }
            // 构建分页条
            sb.append(" ");
        }
        // 将分页条的字符串放置到request之中
        request.setAttribute("bar", sb.toString());  //bar-----------
        // 转发到product_list.jsp页面
        request.getRequestDispatcher("product_list.jsp").forward(request, response);
    }

}
product_list.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@page import="java.util.List"%>
<%@page import="com.lyq.bean.Product"%><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>所有商品信息</title>
<style type="text/css">
    td{font-size: 12px;}
    h2{margin: 0px}
</style>
</head>
<body>
<table align="center" width="450" border="1" height="180" bordercolor="white" bgcolor="black" cellpadding="1" cellspacing="1">
    <tr bgcolor="white">
        <td align="center" colspan="5">
            <h2>所有商品信息</h2>
        </td>
    </tr>
    <tr align="center" bgcolor="#e1ffc1" >
        <td><b>ID</b></td>
        <td><b>商品名称</b></td>
        <td><b>价格</b></td>
        <td><b>数量</b></td>
        <td><b>单位</b></td>
    </tr>
    <%
        List<Product> list = (List<Product>)request.getAttribute("list");
        for(Product p : list){
    %>
    <tr align="center" bgcolor="white">
        <td><%=p.getId()%></td>
        <td><%=p.getName()%></td>
        <td><%=p.getPrice()%></td>
        <td><%=p.getNum()%></td>
        <td><%=p.getUnit()%></td>
    </tr>
    <%    
        }
    %>
    <tr>
        <td align="center" colspan="5" bgcolor="white">
            <%=request.getAttribute("bar")%>
        </td>
    </tr>
</table>
</body>
</html>
index.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>主页</title>
</head>
<body>
    <a href="FindServlet">查看所有商品信息</a>
</body>
</html>

 

 

开发模式:

MVC程序设计理念(Model-View-Controller)

视图层:JSP页面。

控制层:Servlet代码。

模型层:JavaBean代码。

 

 

 

posted @ 2012-08-14 18:38  汤姆是一只猫  阅读(215)  评论(0编辑  收藏  举报