BaseDao的封装

package com.lovo.dao;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.lovo.po.PO;
import com.lovo.po.UserPO;
import com.lovo.util.DBUtil;

public class  BaseDao {

 // 连接对象
 protected Connection con;

 // 操作对象
 protected PreparedStatement pst;

 // 结果集对象
 protected ResultSet rs;

 // 得到连接的方法
 protected Connection getConnection() {

  return DBUtil.getConnection();
 }

 // 关闭连接的方法
 protected void close() {
  try {

   if (rs != null) {
    rs.close();
   }
   if (pst != null) {
    pst.close();
   }
   if (con != null) {
    con.close();
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 // 查询的一种万能的方法,利用反射,参数是sql语句 类模板,值列表

 protected List getPoList(String sql, Class cla, List valueList) {
 
  List list = new ArrayList();
               con = this.getConnection();
  try {
           
   
   // 操作sql
   pst = con.prepareStatement(sql);

   // 如果valuelist不为空的话,则利用setObject方法设置占位符
   if (valueList != null) {

    for (int i = 0; i < valueList.size(); i++) {

     pst.setObject(i + 1, valueList.get(i));

    }

   }

   // 执行sql语句
   rs = pst.executeQuery();

   // 构建对象的list集合
   while (rs.next()) {

    // 得到对象的实例
    Object poObject = cla.newInstance();
                    PO po  = (PO)poObject;
    // 得到属性的集合
    Field[] field = cla.getDeclaredFields();
    for (int i = 0; i < field.length; i++) {

    
     // 得到所有的属性
     Field temp = field[i];

     // 去掉访问修饰 限制
     temp.setAccessible(true);

     // 得到属性名
     String fildName = temp.getName();

     // 将属性的值设置到po对象中,利用getObject方法得到数据库中的值
     temp.set(po, rs.getObject(fildName));
   
     

    }
    
     list.add(po);
   }

  } catch (Exception e) {

   e.printStackTrace();
  }

  return list;

 }

 

 

 // 增删改业务的封装。参数是sql和填充占位符用的 参数对象数组
   protected int executeUpdate(String sql, Object[] param) {
  int j = 0;
  // 建立连接
  con = this.getConnection();

  // 预编译sql
  try {
   pst = con.prepareStatement(sql);

   if (param != null) {

    for (int i = 0; i < param.length; i++) {
     // 设置占位符

     pst.setObject(i + 1, param[i]);
    }

   }

   j = pst.executeUpdate();

  } catch (Exception e) {

   e.printStackTrace();
  }

  return j;

 }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值