利用反射写BaseDao

package com.lyl.dao;

import com.lyl.entity.Question;
import com.lyl.util.EntityUtil;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class BaseDao {
private static final String DRIVERCLASS = “com.mysql.jdbc.Driver”;//加载驱动
private static final String URL = “jdbc:mysql://127.0.0.1:3306/question?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false”;//连接数据库
private static final String USERNAME = “root”;//用户名
private static final String PASSWORD = “root”;//密码

Connection conn = null;
PreparedStatement ps = null;

/**
打开连接和创建驱动
*/
public Connection getConnection() {
Connection connection = null;
try {
Class.forName(DRIVERCLASS);
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);//连接数据库
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}

/**
关闭连接方法
*/
public void closeAll(Connection conn, Statement st, ResultSet rs) {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (st != null)
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
this.conn = null;
this.ps = null;
}

/**
 * 添删改通用的方法
 */
public int execute(String sql, Object... params) {
    Connection conn = getConnection();//打开连接
    PreparedStatement ps = null;//ps为空

    try {
        ps = conn.prepareStatement(sql);//数据库的连接,通过加载驱动获取的连接

        if (params != null) {//循环参数
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i + 1, params[i]);
            }
        }
        int num = ps.executeUpdate();//添删改通用
        return num;

    } catch (SQLException e) {//异常
        e.printStackTrace();
    } finally {
        closeAll(conn, ps, null);//关闭
    }
    return -1;//返回-1
}



/*
 * 查询的通用方法
 *
 */

public <T> List<T> getAll(Class<T> clz, String sql, Object... params) {  //泛型  反射  sql object的参数
    ResultSet rs = getRs(sql, params);//接受rs

    List<T> datas = new ArrayList<>();//泛型的集合

    ResultSetMetaData rsmd = null;// 获取列的信息 (列名, 数据类型);
    try {
        rsmd = rs.getMetaData();//接受列

        int columnCount = rsmd.getColumnCount();//接受他有多少行
        System.out.println("总共有:" + columnCount);//输出行


        if (rs != null) {//判断rs是否为空
            //解析
            while (rs.next()) {//解析
                // 使用反射
                T t = clz.newInstance();

// Question question = new Question();
// 获取所有的set方法
List setMethod = EntityUtil.getAllSetMethod(clz);// 包括了 get
for (int i = 0; i < setMethod.size(); i++) {//过滤
String methodName = setMethod.get(i).getName();
for (int j = 0; j < columnCount; j++) {//循环行数
String cLable = rsmd.getColumnLabel(j + 1);// 从1开始
String cType = rsmd.getColumnTypeName(j + 1);// Varchar
if (methodName.toUpperCase().endsWith(cLable.toUpperCase())) {
// System.out.println(cLable + “:” + cType + “:” + setMethod.get(i).getName() + “:” + EntityUtil.getColumn(cLable, cType, rs));
setMethod.get(i).invoke(t, EntityUtil.getColumn(cLable, cType, rs));
break;
}

                    }

                }

                datas.add(t);
            }
        }
        return datas;//返回集合
    } catch (SQLException e) {//异常
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } finally {//关闭
        closeAll(conn, ps, rs);

    }
    return null;//返回null
}

/**
用来查询(rs)
*/
public ResultSet getRs(String sql, Object… params) {//rs的方法
conn = getConnection();//打开连接
ps = null;//ps为空
ResultSet rs = null;//rs为空
try {
ps = conn.prepareStatement(sql);//数据库的连接,通过加载驱动获取的连接
// 添加参数
if (params != null) {
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
}

        rs = ps.executeQuery();//查询的方法

        return rs;//返回rs
    } catch (SQLException e) {//异常
        e.printStackTrace();
    }
    return null;//返回null

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值