Java Web—-Java Web的数据库操作(二)
Java Web的数据库操作
三、JDBC操作数据库
上一篇介绍了JDBC API,之后就可以通过API来操作数据库,实现对数据库的CRUD操作了。
http://blog.csdn.net/zhai56565/article/details/9794225
下面仅以示例 的方式对数据库操作进行说明
1、 添加数据
使用PreparedStatement添加数据:
- String sql = ”INSERT INTO tb_books(name,price,count,author)valuse(?,?,?,?)”;
- PreparedStatement ps = conn.prepareStatement(sql);
- ps.setString(1, ”西游记”);
- ps.setDouble(2, 66.0);
- ps.setInt(3, 200);
- ps.setString(4, ”吴承恩”);
- int row = ps.executeUpdate();
- if(row > 0)
- System.out.println(“成功添加了” + row + ”条数据”);
使用Statement添加数据:
- String sql = ”INSERT INTO tb_books(name,price,count,author)valuse(“ + ”西游记” + ”,” + 66.0 + ”,” + 200 + ”,” + ”吴承恩” + ”)”;
- ps.close();
- Statement ps = conn.createStatement();
- int row = ps.executeUpdate(sql);
- if(row > 0)
- System.out.println(“成功添加了” + row + ”条数据”);
- ps.close();
2、查询数据
查询数据是通过一个Web项目来演示,通过JDBC查询图书信息表中的图书信息数据,并将其显示在JSP页面中:
创建Book类:
- package com;
- public class Book {
- private int id;
- private String name;
- private double price;
- private int count;
- private String author;
- public Book(int id , String name , double price , int count , String author) {
- this.id = id;
- this.name = name;
- this.price = price;
- this.count = count;
- this.author = 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 getCount(){
- return count;
- }
- public void setCount(int count){
- this.count = count;
- }
- public String getAuthor(){
- return author;
- }
- public void setAuthor(String author){
- this.author = author;
- }
- }
创建Servlet对象FindServlet:
- @WebServlet(“/FindServlet”)
- public class FindServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- public FindServlet() {
- super();
- }
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- doPost(request, response);
- }
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- try {
- Class.forName(“com.mysql.jdbc.Driver”);
- String url = ”jdbc:mysql://localhost:8080/db_test”;
- String username = ”admin”;
- String password = ”123456″;
- Connection connection = DriverManager.getConnection(url, username, password);
- Statement statement = connection.createStatement();
- String sql = ”SELECT * FROM tb_books”;
- ResultSet rs = statement.executeQuery(sql);
- ArrayList<Book> list = new ArrayList<Book>();
- while (rs.next()) {
- Book book = new Book(rs.getInt(“id”) , rs.getString(“name”) ,
- rs.getDouble(“price”) , rs.getInt(“count”) , rs.getString(“author”));
- list.add(book);
- }
- request.setAttribute(“list”, list);
- rs.close();
- statement.close();
- connection.close();
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- //将请求转发到book_list.jsp
- request.getRequestDispatcher(“book_list.jsp”).forward(request, response);
- }
- }
创建book_list.jsp页面:
- <body>
- <table align=”center” width=”450″ border=”2″>
- <tr>
- <td align=”center” colspan=”2″><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>
- <%
- //获取图书信息集合
- ArrayList<Book> list = (ArrayList<Book>)request.getAttribute(“list”);
- if(list == null || list.size() < 1)
- out.print(“没有数据!”);
- else{
- for(Book book : list){
- %>
- <tr align=”center”>
- <td><%= book.getId() %></td>
- <td><%= book.getName() %></td>
- <td><%= book.getPrice() %></td>
- <td><%= book.getCount() %></td>
- <td><%= book.getAuthor() %></td>
- </tr>
- <%
- }
- }
- %>
- </table>
- </body>
创建index.jsp页面:
- <body>
- <a href=”FindServlet”>查看所有图书</a>
- </body>
3、修改数据
修改数据的方法,除了SQL语句外其它都与添加数据相同,其SQL语句为:
UPDATE 表 SET 属性=xxx WHERE 属性=xxx
在实际开发中,通常都是由程序传递SQL语句中的参数,所以修改数据也需要使用PreparedStatement对象进行操作。
4、删除数据
修改数据的方法,除了SQL语句外其它都与添加数据相同,其SQL语句为:
DELETE FROM 表 WHERE 属性=xxx
在实际开发中,通常都是由程序传递SQL语句中的参数,所以删除数据也需要使用PreparedStatement对象进行操作。
5、批处理
JDBC中批处理的原理是将批量的SQL语句一次性发送到数据库中进行执行,从而解决多次与数据库连接所产生的速度瓶颈。下面是一个使用批处理添加数据的方法:
- public int saveBatch() {
- int row = 0;
- try {
- String sql = ”INSERT INTO tb_books(id,name,price,count,anthor) VALUES(?,?,?,?,?)”;
- PreparedStatement ps = connection.prepareStatement(sql);
- for (int i = 0; i < 10; i++) {
- ps.setInt(1, i);
- ps.setString(2, ”书” + i);
- ps.setDouble(3, i*10.5);
- ps.setInt(4, i*20);
- ps.setString(5, ”作者” + i);
- //添加批处理命令
- ps.addBatch();
- }
- //执行批处理操作并返回计数组成的数据
- int[] rows = ps.executeBatch();
- row = rows.length;
- ps.close();
- connection.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return row;
- }
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,依次打开实例、数据库、你的数据库、可编程性、存储过程,右键存储过程选择新建存储过程。这是会弹出文本窗口,内有许多文本,鉴于初学者,将文本内容全部删掉,以下面的代码代替之:
- USE [test]
- GO
- CREATE PROCEDURE findAllBooks
- AS
- BEGIN
- SELECT * from tb_books
- END
- GO
在程序中关键代码如下:
- CallableStatement cs = connection.prepareCall(“{call findAllBook()}”);
- ResultSet resultSet = cs.executeQuery();