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

来源:互联网 发布:淘宝怎么看直播 编辑:程序博客网 时间:2024/06/05 18:27

Java Web的数据库操作

三、JDBC操作数据库

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

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

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

1、 添加数据

      使用PreparedStatement添加数据:

[java] view plaincopyprint?
  1. String sql = "INSERT INTO tb_books(name,price,count,author)valuse(?,?,?,?)";  
  2.   
  3. PreparedStatement ps = conn.prepareStatement(sql);  
  4.   
  5. ps.setString(1"西游记");  
  6.   
  7. ps.setDouble(266.0);  
  8.   
  9. ps.setInt(3200);  
  10.   
  11. ps.setString(4"吴承恩");  
  12.   
  13. int row = ps.executeUpdate();  
  14.   
  15. if(row > 0)  
  16.   
  17.        System.out.println("成功添加了" + row + "条数据");  


      使用Statement添加数据:

[java] view plaincopyprint?
  1. String sql = "INSERT INTO tb_books(name,price,count,author)valuse(" + "西游记" + "," + 66.0 + "," + 200 + "," + "吴承恩" + ")";  
  2.   
  3. ps.close();  
  4.   
  5. Statement ps = conn.createStatement();  
  6.   
  7. int row = ps.executeUpdate(sql);  
  8.   
  9. if(row > 0)  
  10.   
  11.        System.out.println("成功添加了" + row + "条数据");  
  12.   
  13. ps.close();  


2、查询数据

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

      创建Book类:

[java] view plaincopyprint?
  1. package com;  
  2.   
  3.    
  4.   
  5. public class Book {  
  6.   
  7.        private int id;  
  8.   
  9.        private String name;  
  10.   
  11.        private double price;  
  12.   
  13.        private int count;  
  14.   
  15.        private String author;  
  16.   
  17.          
  18.   
  19.        public Book(int id , String name , double price , int count , String author) {  
  20.   
  21.               this.id = id;  
  22.   
  23.               this.name = name;  
  24.   
  25.               this.price = price;  
  26.   
  27.               this.count = count;  
  28.   
  29.               this.author = author;  
  30.   
  31.        }  
  32.   
  33.          
  34.   
  35.        public int getId(){  
  36.   
  37.               return id;  
  38.   
  39.        }  
  40.   
  41.        public void setId(int id){  
  42.   
  43.               this.id = id;  
  44.   
  45.        }  
  46.   
  47.          
  48.   
  49.        public String getName(){  
  50.   
  51.               return name;  
  52.   
  53.        }  
  54.   
  55.        public void setName(String name){  
  56.   
  57.               this.name = name;  
  58.   
  59.        }  
  60.   
  61.          
  62.   
  63.        public double getPrice(){  
  64.   
  65.               return price;  
  66.   
  67.        }  
  68.   
  69.        public void setPrice(double price){  
  70.   
  71.               this.price = price;  
  72.   
  73.        }  
  74.   
  75.          
  76.   
  77.        public int getCount(){  
  78.   
  79.               return count;  
  80.   
  81.        }  
  82.   
  83.        public void setCount(int count){  
  84.   
  85.               this.count = count;  
  86.   
  87.        }  
  88.   
  89.          
  90.   
  91.        public String getAuthor(){  
  92.   
  93.               return author;  
  94.   
  95.        }  
  96.   
  97.        public void setAuthor(String author){  
  98.   
  99.               this.author = author;  
  100.   
  101.        }  
  102.   
  103. }  


      创建Servlet对象FindServlet:

[java] view plaincopyprint?
  1. @WebServlet("/FindServlet")  
  2.   
  3. public class FindServlet extends HttpServlet {  
  4.   
  5.        private static final long serialVersionUID = 1L;  
  6.   
  7.     public FindServlet() {  
  8.   
  9.         super();  
  10.   
  11.     }  
  12.   
  13.    
  14.   
  15.        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  16.   
  17.               doPost(request, response);  
  18.   
  19.        }  
  20.   
  21.          
  22.   
  23.        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  24.   
  25.               try {  
  26.   
  27.                      Class.forName("com.mysql.jdbc.Driver");  
  28.   
  29.                      String url = "jdbc:mysql://localhost:8080/db_test";  
  30.   
  31.                      String username = "admin";  
  32.   
  33.                      String password = "123456";  
  34.   
  35.                      Connection connection = DriverManager.getConnection(url, username, password);  
  36.   
  37.                      Statement statement = connection.createStatement();  
  38.   
  39.                      String sql = "SELECT * FROM tb_books";  
  40.   
  41.                      ResultSet rs = statement.executeQuery(sql);  
  42.   
  43.                      ArrayList<Book> list = new ArrayList<Book>();  
  44.   
  45.                      while (rs.next()) {  
  46.   
  47.                             Book book = new Book(rs.getInt("id") , rs.getString("name") ,  
  48.   
  49.                                           rs.getDouble("price") , rs.getInt("count") , rs.getString("author"));  
  50.   
  51.                             list.add(book);  
  52.   
  53.                      }  
  54.   
  55.                      request.setAttribute("list", list);  
  56.   
  57.                      rs.close();  
  58.   
  59.                      statement.close();  
  60.   
  61.                      connection.close();  
  62.   
  63.               } catch (ClassNotFoundException e) {  
  64.   
  65.                      e.printStackTrace();  
  66.   
  67.               } catch (SQLException e) {  
  68.   
  69.                      e.printStackTrace();  
  70.   
  71.               }  
  72.   
  73.               //将请求转发到book_list.jsp  
  74.   
  75.               request.getRequestDispatcher("book_list.jsp").forward(request, response);  
  76.   
  77.        }  
  78.   
  79. }  


       创建book_list.jsp页面:

[html] view plaincopyprint?
  1. <body>  
  2.   
  3.        <table align="center" width="450" border="2">  
  4.   
  5.               <tr>  
  6.   
  7.                      <td align="center" colspan="2"><h2>所有图书信息</h2></td>  
  8.   
  9.               </tr>  
  10.   
  11.               <tr align="center">  
  12.   
  13.                      <td><b>ID</b></td>  
  14.   
  15.                      <td><b>图书名称</b></td>  
  16.   
  17.                      <td><b>价格</b></td>  
  18.   
  19.                      <td><b>数量</b></td>  
  20.   
  21.                      <td><b>作者</b></td>  
  22.   
  23.               </tr>  
  24.   
  25.               <%  
  26.   
  27.                      //获取图书信息集合  
  28.   
  29.                      ArrayList<Book> list = (ArrayList<Book>)request.getAttribute("list");  
  30.   
  31.                      if(list == null || list.size() < 1)  
  32.   
  33.                             out.print("没有数据!");  
  34.   
  35.                      else{  
  36.   
  37.                             for(Book book : list){  
  38.   
  39.               %>  
  40.   
  41.               <tr align="center">  
  42.   
  43.                      <td><%= book.getId() %></td>  
  44.   
  45.                      <td><%= book.getName() %></td>  
  46.   
  47.                      <td><%= book.getPrice() %></td>  
  48.   
  49.                      <td><%= book.getCount() %></td>  
  50.   
  51.                      <td><%= book.getAuthor() %></td>  
  52.   
  53.               </tr>  
  54.   
  55.               <%  
  56.   
  57.                             }  
  58.   
  59.                      }  
  60.   
  61.               %>  
  62.   
  63.        </table>  
  64.   
  65. </body>  


       创建index.jsp页面:

[html] view plaincopyprint?
  1. <body>  
  2.   
  3. <a href="FindServlet">查看所有图书</a>  
  4.   
  5. </body>  


3、修改数据

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

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

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

4、删除数据

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

              DELETE FROM 表 WHERE 属性=xxx

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

5、批处理

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

      

[java] view plaincopyprint?
  1. public int saveBatch() {  
  2.   
  3.               int row = 0;  
  4.   
  5.               try {  
  6.   
  7.                      String sql = "INSERT INTO tb_books(id,name,price,count,anthor) VALUES(?,?,?,?,?)";  
  8.   
  9.                      PreparedStatement ps = connection.prepareStatement(sql);  
  10.   
  11.                      for (int i = 0; i < 10; i++) {  
  12.   
  13.                             ps.setInt(1, i);  
  14.   
  15.                             ps.setString(2"书" + i);  
  16.   
  17.                             ps.setDouble(3, i*10.5);  
  18.   
  19.                             ps.setInt(4, i*20);  
  20.   
  21.                             ps.setString(5"作者" + i);  
  22.   
  23.                             //添加批处理命令  
  24.   
  25.                             ps.addBatch();  
  26.   
  27.                      }  
  28.   
  29.                      //执行批处理操作并返回计数组成的数据  
  30.   
  31.                      int[] rows = ps.executeBatch();  
  32.   
  33.                      row = rows.length;  
  34.   
  35.                      ps.close();  
  36.   
  37.                      connection.close();  
  38.   
  39.               } catch (SQLException e) {  
  40.   
  41.                      e.printStackTrace();  
  42.   
  43.               }  
  44.   
  45.               return row;  
  46.   
  47.        }  


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

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

 

       在程序中关键代码如下:

[java] view plaincopyprint?
  1. CallableStatement cs = connection.prepareCall("{call findAllBook()}");  
  2.   
  3. ResultSet resultSet = cs.executeQuery();  

 

 

下一节介绍JDBC在Java Web中的应用

0 0
原创粉丝点击