通用baseDao

package com.springboot.layui.demo.jdbc.bean;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class BaseDao {
    private  String Driver_NAME = "com.mysql.jdbc.Driver";//驱动类
    private  String URL = "jdbc:mysql://127.0.0.1:3306/stu";//数据库连接地址
    private  String USER = "root";//用户名
    private  String PASS = "";//密码 没有可以不写

    private  Connection conn = null;
    private  PreparedStatement ps = null;
    private  ResultSet rs = null;

    private  void close() throws Exception{
        if (rs!=null){
            rs.close();
        }
        if (ps!=null){
            ps.close();
        }
        if (conn!=null){
            conn.close();
        }
    }
     void getConn() {
        try {
            Class.forName(Driver_NAME);
            conn = DriverManager.getConnection(URL, USER, PASS);
        } catch (ClassNotFoundException e) {
            System.out.println("没有找到驱动类");
            e.printStackTrace();
        } catch (SQLException e) {
            System.out.println("创建连接错误");
            e.printStackTrace();
        }
    }
    public  int updateOrInsertOrDelete(String sql, Object... objects) throws Exception{
        getConn();
        ps = conn.prepareStatement(sql);
        for (int i = 0; i < objects.length; i++) {
            ps.setObject(i+1, objects[i]);
        }
        int i = ps.executeUpdate();
        close();
        return i;
    }

    public  <T> List<T> findAll(String sql, Class<T> tClass, Object... objects) throws Exception {
        getConn();
        List<T> list = new ArrayList<>();
        ps = conn.prepareStatement(sql);
        for (int i = 0; i < objects.length; i++) {
            ps.setObject(i + 1, objects[i]);
        }
        rs = ps.executeQuery();
        while (rs.next()) {
            T t = rsToBeas(tClass, rs);
            list.add(t);
        }
        close();
        return list;
    }

    private  <T> T rsToBeas(Class<T> tClass, ResultSet rs) throws Exception {
        T t = null;
        /*
            Demo demo=new Demo() == Demo demo=Demo.Class.newInstance()
            把类实例化出来
         */
        t = tClass.newInstance();
        ResultSetMetaData metaData = rs.getMetaData();//返回查询的源数据
        int columnCount = metaData.getColumnCount();//返回查询数据的字段数
        for (int i = 0; i < columnCount; i++) {
            String catalogName = metaData.getColumnLabel(i+1);//根据字段数返回字段名称
            Object object = rs.getObject(catalogName);//根据name获取字段数据
            Field field = tClass.getDeclaredField(catalogName);//利用反射得到实例化对象的属性这个属性,并且这个属性要和表的字段或者别名要一样才能赋值
            field.setAccessible(true);//设置权限
            field.set(t, object);//修改数据
        }
        return t;
    }
}

jdbc的通用dao只需要提供sql语句和参数就行了

上一篇:@Resource 注解的使用


下一篇:queryrunner Basedao的使用