DAO写法

package com.tarena.dao;

import java.util.List;

import com.tarena.entity.Product;

public interface ProductDAO {
   public List<Product> queryAllProducts();
   
   public Product queryProductByProductNo(int productNo);
}

 

package com.tarena.dao;

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

import com.tarena.entity.Product;
import com.tarena.util.ConnectionUtil;

public class ProductDAOImpl implements ProductDAO {

 public List<Product> queryAllProducts() {
  Connection conn =null;
  PreparedStatement pstmt = null;
  ResultSet rs = null;
  List<Product> products = new ArrayList<Product>();
       
  try{
   conn = ConnectionUtil.getConnection();
   String sql = "select product_no,product_name,product_price from t_product";
   pstmt = conn.prepareStatement(sql);
   rs = pstmt.executeQuery();
    while(rs.next()){
      Product product = new Product();
      product.setProductNo(rs.getInt(1));
      product.setProductName(rs.getString(2));
      product.setProductPrice(rs.getInt(3));
      products.add(product);
         }
   
   return products;
  }catch(Exception e){
   e.printStackTrace();
   return null;
  }
 }

 public Product queryProductByProductNo(int productNo) {
  Connection conn =null;
  PreparedStatement pstmt = null;
  ResultSet rs = null;
  Product product = null;
       
  try{
   conn = ConnectionUtil.getConnection();
   String sql = "select product_no,product_name,product_price from t_product where product_no=?";
   pstmt = conn.prepareStatement(sql);
   pstmt.setInt(1, productNo);
   rs = pstmt.executeQuery();
    if(rs.next()){
      product = new Product();
      product.setProductNo(rs.getInt(1));
      product.setProductName(rs.getString(2));
      product.setProductPrice(rs.getInt(3));
    }
   
   return product;
  }catch(Exception e){
   e.printStackTrace();
   return null;
  }
 }
}

你可能感兴趣的:(java,DAO,sql)