JDBC封装,用泛型和反射实现.



import com.mysql.jdbc.Connection;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class DBUtils {

    private static Properties properties = new Properties();
    static {
        //1.注册驱动  告诉jdbc我们使用哪一个数据库厂商的驱动
        try {
            //1.1 读取文件中的信息
            FileInputStream in = null;
            try {
                in = new FileInputStream("智慧公交页面模板/swing_test/resource/properties");
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
            // 1.2  Properties对象中有一个load方法
            properties.load(in);  //将文件相关的信息加载到properties 对象中
            Class.forName(properties.getProperty("driverClassName"));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    Connection connection = null;
    PreparedStatement st = null;
    ResultSet rs = null;
    //得到connection对象
    public  Connection getConnection()  {
        //2.通过驱动管理器获取一个链接
        try {
            connection = (Connection) DriverManager.getConnection(properties.getProperty("url"),
                    properties.getProperty("username"), properties.getProperty("password"));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return  connection;
    }
    //关闭链接
    public  void release(){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            rs =null; //让jvm来回收它
        }
        if(st!=null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            st =null; //让jvm来回收它
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            connection =null; //让jvm来回收它
        }
    }

    //增删改操作
    public int excuteUpdate(String sql,Object... params)   {
        int result = -1;
        try {
            //2. 创建连接
            connection = getConnection();
            //3. 创建statement对象
            //这个里包括了? ,所以需要参数指定
            st = connection.prepareStatement(sql);

            //要把参数加到PreparedStatement对象中
            //pst.setString(1,username);
            // pst.setString(2,pwd);
            for (int i = 0; i < params.length; i++) {
                st.setObject((i + 1), params[i]);
            }
            result = st.executeUpdate();

            //4. release 释放资源
            release();
        }catch (SQLException e){
            e.printStackTrace();
            result = -1;
        }finally {
            return result;
        }
    }

    //查询操作
    public <T> List<T> excuteQuery(String sql, Class<T> c, Object... prarms){
        //创建一个集合,存放所有的结果对象
        List<T> list  = new ArrayList<>();
        try {
            connection = getConnection();
            //	3. 获得执行对象  Statement
            // 查询 里的sql语句也可以能有参数
            st = connection.prepareStatement(sql);
            //添加参数
            for (int i = 0; i < prarms.length; i++) {
                st.setObject((i + 1), prarms[i]);
            }
            //	4. 执行sql并获得结果集(ResultSet)
            rs = st.executeQuery();
            // 4.1 得到结果集的元数据
            ResultSetMetaData ms = rs.getMetaData();
            //列的数量
            int colCount = ms.getColumnCount();
            // 处理结果
            while (rs.next()){
//                int i = 1;
                //添加一个 T类的实例
                T t = c.getDeclaredConstructor().newInstance();
                // 1. 得到结果集,列名数组
                //2. 循环列名
                //   循环体里,根据列名,去找对象的对应的字段 ,然后在进行赋值
                for(int i=1;i<=colCount;i++){
                    Object value = rs.getObject(i);
                    if(value!=null){
                        //将这对应的值,放到对象对应的字段中
                        String colName = ms.getColumnName(i);
                        //通过反射,设置字段的值
                        //要求结果的列名,与实体对象的属性(字段名)相同
                        Field field = c.getDeclaredField(colName);
                        // 跳出java的语法检查
                        field.setAccessible(true);
                        // 给字段设置对应的值
                        field.set(t,value);
                    }
                }

                list.add(t);


                //给实例对象的每个属性,赋值
                // 方法一: 获取所有字段进行赋值,这个要求字段与数据的列的顺序要求一致
//                Field[] Fields = c.getDeclaredFields(); //获取所有的字段
//                for(Field field : Fields){
//                    //缺点: 实体的字段 与数据查询 出来的字段要一一对应
//                    //思路: 如果不对应怎么?
//                    // 最好,可以得到结果集的列名,根据列名,给对应的字段赋值
//
//                    // 这里值 ,应该从结果集
//                    field.set(t,rs.getObject(i++));
//                }
                //T对象加入到list中
            }
            // 	5. 处理结果集
            release();
        }catch (Exception e){
            e.printStackTrace();
            list = null;
        } finally {
            return list;
        }
    }


}

 可之间使用;

举例:

增删改操作:





    //引入工具类
    DBUtils dbUtils = new DBUtils();
    
    //编写sql语句,增 删 改 都可以
    String sql = "INSERT INTO base_card_info (card_id,user_id,dept)VALUES(?,?,?)";


      //有几个问号就是要改几个值,下面调用就输入几个值
    //调用 增 删 改 公用的方法
    int re  = dbUtils.excuteUpdate(sql,carId,user_id,dept);
            
    
}

查询操作:

        //导入工具类
        DBUtils dbUtils = new DBUtils();
  
        //写sql语句
        String sql = "SELECT * FROM base_card_out  WHERE out_time BETWEEN ?AND?";

        //?是你要查询时的条件,由方法传入
        List list = dbUtils.excuteQuery(sql, SelectCareVo.class,loginTime,endLoginTime);
        
        //这里第二个参数是实体类的映射

  • 14
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值