反射实战 使用反射,对JDBC进行强封装

JDBC 强封装

苦于学习了反射,却不知道在哪里使用?我这里给大伙整一个反射的小型实战
是使用反射封装JDBC的操作
因为查询需要支持复杂查询,所以没有办法去封装
剩下的CUD操作,都使用反射进行了强封装
如果你能看懂,并自己写下对用的代码,那么,你的反射就入门了!

封装

类装载与初始化

"com.mysql.cj.jdbc.Driver"是在 Mysql8 以后,使用的

数据库连接和用户名、密码,需要按照个人需求修改

static {
   
        try {
   
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
   
            e.printStackTrace();
        }
    }

    private static final String url="jdbc:mysql://localhost:3306/SQLStudy?serverTimezone=UTC";
    private static final String name="admin";
    private static final String password="123";
    //受影响的行数
    private int count=0;

    private Connection conn = null;
    private PreparedStatement stmt = null;
    private ResultSet resultSet = null;

获取连接和状态

这些都是死代码,没什么好说的

/**
     * 获取数据库连接
     * @return
     */
    protected Connection getConnection() {
   
        try {
   
            conn = DriverManager.getConnection(url, name, password);
        } catch (SQLException throwables) {
   
            throwables.printStackTrace();
        }
        return conn;
    }

    /**
     * 获取preparedStatement
     * @param sql
     * @param list
     * @return
     */
    protected PreparedStatement getStatement(String sql, List list) {
   
        getConnection();
        try {
   
            stmt = conn.prepareStatement(sql);
        } catch (SQLException throwables) {
   
            throwables.printStackTrace();
        }
        if (list!=null && list.size()>0) {
   
            for (int i = 0; i < list.size(); i++) {
   
                try {
   
                    stmt.setObject(i+1,list.get(i));
                } catch (SQLException throwables) {
   
                    throwables.
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FARO_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值