JDBC封装增删改查

思路:

1.创建jdbc.properties文件

jdbc.url=jdbc:mysql:///jtdb?characterEncoding=utf-8&serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=root

2.创建JDBCUtil工具类用于获取连接,关闭连接:

package com.cn.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtil {
    private static String url;
    private static String username;
    private static String password;
    private Connection conn = null;
    public static  Connection getConnection() throws IOException, SQLException {
        InputStream read = ClassLoader.getSystemResourceAsStream("./properties/jdbc.properties");
        Properties props = new Properties();
        props.load(read);
        url=props.getProperty("jdbc.url");
        username=props.getProperty("jdbc.username");
        password=props.getProperty("jdbc.password");
        return DriverManager.getConnection(url,username,password);
    }
    public static void CloseConn(Connection conn, PreparedStatement ps, ResultSet rs){
        try {
                if(rs!=null){
                    rs.close();
                }
                if(ps!=null){
                    ps.close();
                }
                if(conn!=null){
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

    }

}

3.在Dao接口中写两个方法作为一个统一的入口:

package com.cn.Dao;

import java.util.List;

public interface UserDao {

    int executeUpdate(String sql, Object... params);

    <T>List executeQueue(String sql, Class<T> cls, Object... params);

 4.创建实现类,实现两个方法

(1)封装增删改方法:

 @Override
    public int executeUpdate(String sql, Object... params) {
        Connection conn=null;
        PreparedStatement ps=null;
        try {
            //获取连接
            conn = JDBCUtil.getConnection();
            ps = conn.prepareStatement(sql);
            //获取preparedStatement()参数
            for(int i=0;i<params.length;i++){
                ps.setObject(i+1,params[i]);
            }
            //执行sql并返回影响的行数
            return ps.executeUpdate();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.CloseConn(conn,ps,null);
        }

        return 0;
    }

(2)封装查询方法:利用反射、对应实体类的set方法实现

 @Override
    public <T> List executeQueue(String sql, Class<T> cls, Object... params) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        T t=null;
        List<T> list = new ArrayList<>();
        try {
            conn = JDBCUtil.getConnection();
            ps = conn.prepareStatement(sql);
            for(int i=0;i< params.length;i++){
                ps.setObject(i+1,params[i]);
            }
            rs = ps.executeQuery();
            ResultSetMetaData data = rs.getMetaData();//获取数据库元数据的集合
            int count1 = data.getColumnCount();//获取数据库列数
            while (rs.next()) {
                    t = cls.getConstructor().newInstance();//通过反射构造实例化对象
                for (int i = 0; i < count1; i++) {
                    String columnName = data.getColumnName(i + 1);//获取数据库字段名
                    String columnLabel = data.getColumnLabel(i + 1);//获取数据库字段别名(一般使别名和pojo对象属性一致)
                    //System.out.println(columnName+"/"+columnLabel);
                    //拼接pojo对象的set方法
                    String methodName = "set"+columnLabel.substring(0,1).toUpperCase()+columnLabel.substring(1);
                    //获取实例对象里对应的set方法
                    Method method = getMethod(cls, methodName);
                    if(method!=null){
                        method.invoke(t,rs.getObject(columnLabel));//执行set方法为实例对象赋值
                    }
                }
                list.add(t);
            }

            return list;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.CloseConn(conn,ps,rs);
        }

        return null;
    }
    public <T>Method getMethod(Class<T> cls,String methodName){
        Method[] methods = cls.getMethods();//获取字节码对象的方法集合
        for (Method method : methods) {//通过对比方法名找出对应的set方法
            if(method.getName().equals(methodName)){
                return method;
            }
        }
        return null;
    }

5.创建测试类测试:

(1)测试查询方法:

 (2)测试修改方法:

 好了,不懂就问,有错就提哈,欢迎打扰。

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值