1. 程式人生 > >簡單學習 JDBC的DAO模式

簡單學習 JDBC的DAO模式

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.oracle.vo.Book;

public class BookDaoImpl extends BaseDao implements BookDao {

	//插入記錄
	@Override
	public void save(Book book) {
		this.executeSql("insert into tb_book values(null,?,?)", book.getBookName(),book.getPrice());
		
	}

	//更新記錄
	@Override
	public void update(Book book) {

		this.executeSql("update tb_book set bookname=?,price=? where bookid=?", book.getBookName(),book.getPrice(),book.getBookid());
	}

	//刪除記錄
	@Override
	public void delete(Integer bookid) {
		this.executeSql("Delete from tb_book where bookid=?", bookid);
	}

	//查詢所有記錄
	@Override
	public List<Book> getAllBook() {
		
		List<Book> list=new ArrayList<Book>();
		Connection conn=this.getConnection();
		PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			//查詢出所有的記錄,按照bookid排序
			ps=conn.prepareStatement("select bookid,bookname,price from tb_book order by bookid");
			rs=ps.executeQuery();
			while(rs.next()) {
				Book b=new Book();//建立一個vo物件儲存記錄的資訊
				b.setBookid(rs.getInt("bookid"));
				b.setBookName(rs.getString("bookname"));
				b.setPrice(rs.getInt("price"));
				list.add(b);//每條記錄新增到list中
			}
			
			return list;
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			this.close(rs);
			this.close(ps);
			this.close(conn);
		}
		
		return list;
	}

	//根據id查詢單條記錄
	@Override
	public Book getByBookid(Integer bookid) {
		Connection conn=this.getConnection();
		PreparedStatement ps=null;
		ResultSet rs=null;
		Book b=new Book();
		try {
			ps=conn.prepareStatement("select bookid,bookname,price from tb_book where bookid=?");
			ps.setInt(1, bookid);
			rs=ps.executeQuery();
			if(rs.next()) {
				b.setBookid(rs.getInt("bookid"));
				b.setBookName(rs.getString("bookname"));
				b.setPrice(rs.getInt("price"));
			}
			
			return b;
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			this.close(rs);
			this.close(ps);
			this.close(conn);
		}
		return b;
	}

	//分頁查詢
	@Override
	public List<Book> getByPage(Integer page, Integer number) {
		List<Book> list=new ArrayList<Book>();
		Connection conn=this.getConnection();
		PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			ps=conn.prepareStatement("select bookid,bookname,price from tb_book order by bookid limit ?,?");
			ps.setInt(1,(page-1)*number);
			ps.setInt(2, number);
			rs=ps.executeQuery();
			while(rs.next()) {
				Book b=new Book();
				b.setBookid(rs.getInt("bookid"));
				b.setBookName(rs.getString("bookname"));
				b.setPrice(rs.getInt("price"));
				list.add(b);
			}
			
			return list;
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			this.close(rs);
			this.close(ps);
			this.close(conn);
		}
		
		return list;
	}

	

}