Java Web—-Java Web的数据库操作(二)



Java Web—-Java Web的数据库操作(二)

Java Web的数据库操作

三、JDBC操作数据库

上一篇介绍了JDBC API,之后就可以通过API来操作数据库,实现对数据库的CRUD操作了。

http://blog.csdn.net/zhai56565/article/details/9794225

下面仅以示例 的方式对数据库操作进行说明

1、 添加数据

使用PreparedStatement添加数据:

  1. String sql = ”INSERT INTO tb_books(name,price,count,author)valuse(?,?,?,?)”;
  2. PreparedStatement ps = conn.prepareStatement(sql);
  3. ps.setString(1, ”西游记”);
  4. ps.setDouble(2, 66.0);
  5. ps.setInt(3, 200);
  6. ps.setString(4, ”吴承恩”);
  7. int row = ps.executeUpdate();
  8. if(row > 0)
  9.        System.out.println(“成功添加了” + row + ”条数据”);

 

使用Statement添加数据:

  1. String sql = ”INSERT INTO tb_books(name,price,count,author)valuse(“ + ”西游记” + ”,” + 66.0 + ”,” + 200 + ”,” + ”吴承恩” + ”)”;
  2. ps.close();
  3. Statement ps = conn.createStatement();
  4. int row = ps.executeUpdate(sql);
  5. if(row > 0)
  6.        System.out.println(“成功添加了” + row + ”条数据”);
  7. ps.close();

 

2、查询数据

查询数据是通过一个Web项目来演示,通过JDBC查询图书信息表中的图书信息数据,并将其显示在JSP页面中:

创建Book类:

  1. package com;
  2. public class Book {
  3.        private int id;
  4.        private String name;
  5.        private double price;
  6.        private int count;
  7.        private String author;
  8.        public Book(int id , String name , double price , int count , String author) {
  9.               this.id = id;
  10.               this.name = name;
  11.               this.price = price;
  12.               this.count = count;
  13.               this.author = author;
  14.        }
  15.        public int getId(){
  16.               return id;
  17.        }
  18.        public void setId(int id){
  19.               this.id = id;
  20.        }
  21.        public String getName(){
  22.               return name;
  23.        }
  24.        public void setName(String name){
  25.               this.name = name;
  26.        }
  27.        public double getPrice(){
  28.               return price;
  29.        }
  30.        public void setPrice(double price){
  31.               this.price = price;
  32.        }
  33.        public int getCount(){
  34.               return count;
  35.        }
  36.        public void setCount(int count){
  37.               this.count = count;
  38.        }
  39.        public String getAuthor(){
  40.               return author;
  41.        }
  42.        public void setAuthor(String author){
  43.               this.author = author;
  44.        }
  45. }

创建Servlet对象FindServlet:

  1. @WebServlet(“/FindServlet”)
  2. public class FindServlet extends HttpServlet {
  3.        private static final long serialVersionUID = 1L;
  4.     public FindServlet() {
  5.         super();
  6.     }
  7.        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  8.               doPost(request, response);
  9.        }
  10.        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  11.               try {
  12.                      Class.forName(“com.mysql.jdbc.Driver”);
  13.                      String url = ”jdbc:mysql://localhost:8080/db_test”;
  14.                      String username = ”admin”;
  15.                      String password = ”123456″;
  16.                      Connection connection = DriverManager.getConnection(url, username, password);
  17.                      Statement statement = connection.createStatement();
  18.                      String sql = ”SELECT * FROM tb_books”;
  19.                      ResultSet rs = statement.executeQuery(sql);
  20.                      ArrayList<Book> list = new ArrayList<Book>();
  21.                      while (rs.next()) {
  22.                             Book book = new Book(rs.getInt(“id”) , rs.getString(“name”) ,
  23.                                           rs.getDouble(“price”) , rs.getInt(“count”) , rs.getString(“author”));
  24.                             list.add(book);
  25.                      }
  26.                      request.setAttribute(“list”, list);
  27.                      rs.close();
  28.                      statement.close();
  29.                      connection.close();
  30.               } catch (ClassNotFoundException e) {
  31.                      e.printStackTrace();
  32.               } catch (SQLException e) {
  33.                      e.printStackTrace();
  34.               }
  35.               //将请求转发到book_list.jsp
  36.               request.getRequestDispatcher(“book_list.jsp”).forward(request, response);
  37.        }
  38. }

创建book_list.jsp页面:

  1. <body>
  2.        <table align=”center” width=”450″ border=”2″>
  3.               <tr>
  4.                      <td align=”center” colspan=”2″><h2>所有图书信息</h2></td>
  5.               </tr>
  6.               <tr align=”center”>
  7.                      <td><b>ID</b></td>
  8.                      <td><b>图书名称</b></td>
  9.                      <td><b>价格</b></td>
  10.                      <td><b>数量</b></td>
  11.                      <td><b>作者</b></td>
  12.               </tr>
  13.               <%
  14.                      //获取图书信息集合
  15.                      ArrayList<Book> list = (ArrayList<Book>)request.getAttribute(“list”);
  16.                      if(list == null || list.size() < 1)
  17.                             out.print(“没有数据!”);
  18.                      else{
  19.                             for(Book book : list){
  20.               %>
  21.               <tr align=”center”>
  22.                      <td><%= book.getId() %></td>
  23.                      <td><%= book.getName() %></td>
  24.                      <td><%= book.getPrice() %></td>
  25.                      <td><%= book.getCount() %></td>
  26.                      <td><%= book.getAuthor() %></td>
  27.               </tr>
  28.               <%
  29.                             }
  30.                      }
  31.               %>
  32.        </table>
  33. </body>

创建index.jsp页面:

  1. <body>
  2. <a href=”FindServlet”>查看所有图书</a>
  3. </body>

 

3、修改数据


修改数据的方法,除了SQL语句外其它都与添加数据相同,其SQL语句为:

UPDATE 表 SET 属性=xxx WHERE 属性=xxx

在实际开发中,通常都是由程序传递SQL语句中的参数,所以修改数据也需要使用PreparedStatement对象进行操作。

4、删除数据

修改数据的方法,除了SQL语句外其它都与添加数据相同,其SQL语句为:

DELETE FROM 表 WHERE 属性=xxx

在实际开发中,通常都是由程序传递SQL语句中的参数,所以删除数据也需要使用PreparedStatement对象进行操作。

5、批处理

JDBC中批处理的原理是将批量的SQL语句一次性发送到数据库中进行执行,从而解决多次与数据库连接所产生的速度瓶颈。下面是一个使用批处理添加数据的方法:

  1. public int saveBatch() {
  2.               int row = 0;
  3.               try {
  4.                      String sql = ”INSERT INTO tb_books(id,name,price,count,anthor) VALUES(?,?,?,?,?)”;
  5.                      PreparedStatement ps = connection.prepareStatement(sql);
  6.                      for (int i = 0; i < 10; i++) {
  7.                             ps.setInt(1, i);
  8.                             ps.setString(2, ”书” + i);
  9.                             ps.setDouble(3, i*10.5);
  10.                             ps.setInt(4, i*20);
  11.                             ps.setString(5, ”作者” + i);
  12.                             //添加批处理命令
  13.                             ps.addBatch();
  14.                      }
  15.                      //执行批处理操作并返回计数组成的数据
  16.                      int[] rows = ps.executeBatch();
  17.                      row = rows.length;
  18.                      ps.close();
  19.                      connection.close();
  20.               } catch (SQLException e) {
  21.                      e.printStackTrace();
  22.               }
  23.               return row;
  24.        }

6、调用存储过程

在JDBC API中提供了调用存储过程的方法,通过CallableStatement对象进行操作。CallableStatement对象位于java.sql包中,它继承于Statement对象,主要用于执行数据库中定义的存储过程,其调用方法如下:

{call <procedure-name>[(<arg1>,<arg2>,…)]}

其中arg1、arg2为存储过程中的参数,如果存储过程中需要传递参数,可以对其进行赋值操作。

存储过程是一个SQL语句和可选控制流语句的预编译集合。编译完成后存放在数据库中,这样就省去了执行SQL语句时对SQL语句进行编译所花费的时间。在执行存储过程时只需要将参数传递到数据库中,而不需要将整条SQL语句都提交给数据库,从而减少了网络传输的流量,提高了程序的运行速度。

各种数据库创建存储过程的方法并非一致,下面以SQL Server 2012调用存储过程的方法做讲解,其他数据库请参考其帮助文档:

首先打开 SQL Server Management Studio,依次打开实例、数据库、你的数据库、可编程性、存储过程,右键存储过程选择新建存储过程。这是会弹出文本窗口,内有许多文本,鉴于初学者,将文本内容全部删掉,以下面的代码代替之:

  1. USE [test]
  2. GO
  3. CREATE PROCEDURE findAllBooks
  4. AS
  5. BEGIN
  6.     SELECT * from tb_books
  7. END
  8. GO

 

在程序中关键代码如下:

  1. CallableStatement cs = connection.prepareCall(“{call findAllBook()}”);
  2. ResultSet resultSet = cs.executeQuery();