package com.dao; import java.sql.*; import javax.sql.*; import javax.naming.*; import com.demo.BookBean; public class BookDao { private static InitialContext context = null; private DataSource dataSource = null; public BookDao() { try { if (context == null) { context = new InitialContext(); } dataSource = (DataSource)context.lookup("java:comp/env/jdbc/demo"); } catch (NamingException e) { e.printStackTrace(); } } // 根据书号查询图书信息 public BookBean searchBook(String bookid) { Connection dbconn = null; PreparedStatement pstmt = null; ResultSet rst = null; BookBean book = new BookBean(); try { dbconn = dataSource.getConnection(); pstmt = dbconn.prepareStatement("SELECT * FROM books WHERE bookid=?"); pstmt.setString(1, bookid); rst = pstmt.executeQuery(); if (rst.next()) { book.setBookid(rst.getString("bookid")); book.setTitle(rst.getString("title")); book.setAuthor(rst.getString("author")); book.setPublisher(rst.getString("publisher")); book.setPrice(rst.getDouble("price")); return book; } else { return null; } } catch (SQLException se) { se.printStackTrace(); return null; } finally { try { if (rst != null) rst.close(); if (pstmt != null) pstmt.close(); if (dbconn != null) dbconn.close(); } catch (SQLException se) { se.printStackTrace(); } } } // 插入一本图书记录 public boolean insertBook(BookBean book) { Connection dbconn = null; PreparedStatement pstmt = null; try { dbconn = dataSource.getConnection(); pstmt = dbconn.prepareStatement("INSERT INTO books VALUES(?,?,?,?,?)"); pstmt.setString(1, book.getBookid()); pstmt.setString(2, book.getTitle()); pstmt.setString(3, book.getAuthor()); pstmt.setString(4, book.getPublisher()); pstmt.setDouble(5, book.getPrice()); int result = pstmt.executeUpdate(); return result > 0; } catch (SQLException se) { se.printStackTrace(); return false; } finally { try { if (pstmt != null) pstmt.close(); if (dbconn != null) dbconn.close(); } catch (SQLException se) { se.printStackTrace(); } } } }