JDBC 使用优化以及工具类封装

获取连接工具类 v1

// JdbcUtils.java
package com.binxin.api.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/*
 * 内部包含一个连接池对象,并且对外提供获取连接和回收连接的方法!
 *
 * 工具类的方法,推荐写成静态,外部调用会更加方便!
 *
 * 实现:
 *   属性 连接池对象 [实例化一次]
 *       单例模式
 *       static{
 *           全局调用一次
 *       }
 *   方法
 *       对外提供连接的方式
 *       回收外部传入的方法
 * */
public class JdbcUtils {
    private static DataSource dataSource = null;    //连接池对象

    static {
        //初始化连接池对象
        Properties properties = new Properties();
        InputStream ips = JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
        try {
            properties.load(ips);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        try {
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /*
    * 对外提供连接的方法
    * */
    public static Connection connection() throws SQLException {
        return dataSource.getConnection();
    }

    public static void freeConnection(Connection connection) throws SQLException {
        connection.close(); //回收连接
    }
}
// JdbcCurdPart.java
package com.binxin.api.utils;

import java.sql.Connection;
import java.sql.SQLException;

/*
* 基于工具类的curd
* */
public class JdbcCurdPart {
    public void testInsert() throws SQLException {
        Connection connection=JdbcUtils.connection();

        //数据库的curd动作

        JdbcUtils.freeConnection(connection);
    }
}

获取连接工具类 v2

  1. 同一个线程不同方法获取同一个链接
package com.binxin.api.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/*
 * 内部包含一个连接池对象,并且对外提供获取连接和回收连接的方法!
 *
 * 工具类的方法,推荐写成静态,外部调用会更加方便!
 *
 * 实现:
 *   属性 连接池对象 [实例化一次]
 *       单例模式
 *       static{
 *           全局调用一次
 *       }
 *   方法
 *       对外提供连接的方式
 *       回收外部传入的方法
 *
 * 利用线程本地变量,存储连接信息!确保一个线程的多个方法可以获取同一个connection!
 * 事务操作的时候service和dao属于同一个线程,不同再传递参数了
 * */
public class JdbcUtilsV2 {
    private static DataSource dataSource = null;    //连接池对象

    private static ThreadLocal<Connection> tl = new ThreadLocal<>();

    static {
        //初始化连接池对象
        Properties properties = new Properties();
        InputStream ips = JdbcUtilsV2.class.getClassLoader().getResourceAsStream("druid.properties");
        try {
            properties.load(ips);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        try {
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /*
     * 对外提供连接的方法
     * */
    public static Connection connection() throws SQLException {
        //线程本地变量中是否存在
        Connection connection = tl.get();

        if (connection == null) {
            connection = dataSource.getConnection();
            tl.set(connection);
        }

        return connection;
    }

    public static void freeConnection() throws SQLException {
        Connection connection = tl.get();
        if (connection != null) {
            tl.remove();
            connection.setAutoCommit(true);
            connection.close(); //回收连接
        }
    }
}

高级应用封装 BaseDao

package com.binxin.api.utils;

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

/*
 * 一个简化非DQL
 * 一个简化DQL
 *
 * */
public class BaseDao {
    public int excuteUpdate(String sql, Object... params) throws SQLException {
        Connection connection = JdbcUtilsV2.connection();

        // 创建preparedStatement.并且传入sql语句结果
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        // 占位符赋值
        for (int i = 1; i < params.length; i++) {
            preparedStatement.setObject(i, params[i - 1]);
        }

        // 发送SQL语句
        int rows = preparedStatement.executeUpdate();

        // 关闭连接
        preparedStatement.close();
        if (connection.getAutoCommit()) {
            JdbcUtilsV2.freeConnection();
        }

        return rows;
    }

    /*
     * <T>声明一个泛型,不确定类型
     * */
    public <T> List<T> excuteQuery(Class<T> clazz, String sql, Object... params) throws SQLException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        // 获取连接
        Connection connection = JdbcUtilsV2.connection();

        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        // 占位符赋值
        if (params != null && params.length > 0) {
            for (int i = 1; i < params.length; i++) {
                preparedStatement.setObject(i, params[i - 1]);
            }
        }

        // 发送SQL语句
        ResultSet resultSet = preparedStatement.executeQuery();
        // 结果集解析
        List<T> list = new ArrayList<>();

        //获取列的信息对象
        ResultSetMetaData metaData = resultSet.getMetaData();
        //获取列的个数
        int columnCount = metaData.getColumnCount();

        while (resultSet.next()) {
            T t= clazz.newInstance();

            //自动取值
            for (int i = 1; i <= columnCount; i++) {
                //获取对象的属性值
                Object value = resultSet.getObject(i);
                //获取对象的属性名
                String columnLabel = metaData.getColumnLabel(i);

                Field field = clazz.getDeclaredField(columnLabel);
                field.setAccessible(true);
                field.set(t, value);
            }
            list.add(t);
        }
        //关闭资源
        resultSet.close();
        preparedStatement.close();
        if (connection.getAutoCommit()){
            JdbcUtilsV2.freeConnection();
        }

        return list;
    }
}
  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
引用\[1\]中提到了JDBC工具类的代码实现,其中使用了ResourceBundle进行资源的绑定,主要是绑定到jdbc.properties文件,方便读取相关配置信息。工具类的代码实现包括加载驱动、关闭资源、建立数据库连接、执行预编译的SQL语句、处理结果以及释放资源等步骤。\[1\] 引用\[2\]中提到了在src根目录下创建了一个db.properties文件,其中包含了数据库的相关配置信息,如用户名、密码、驱动名和URL等。\[2\] 引用\[3\]中给出了一个c3p0-config.xml配置文件的示例,其中包含了默认的连接池配置信息,包括用户名、密码、驱动类、JDBC URL以及连接池的参数配置等。\[3\] 综合以上引用内容,可以得出jdbc工具类的最终版应该包括以下几个步骤: 1. 加载驱动:使用Class.forName()方法加载数据库驱动。 2. 建立数据库连接:读取jdbc.properties文件或者db.properties文件中的配置信息,包括用户名、密码、驱动名和URL等,使用DriverManager.getConnection()方法建立数据库连接。 3. 执行SQL语句:根据具体需求,编写SQL语句,并使用PreparedStatement进行预编译。 4. 处理结果:根据SQL语句的类型,使用ResultSet获取查询结果或者使用executeUpdate()方法执行更新操作。 5. 释放资源:关闭ResultSet、PreparedStatement和Connection等资源,释放数据库连接。 以上是一个简单的jdbc工具类的最终版实现,具体的代码实现可以根据具体需求进行调整和扩展。 #### 引用[.reference_title] - *1* [JDBC工具类 以及使用JDBC工具类 一般开发不可能直接使用 JDBC 了解即可](https://blog.csdn.net/qq_40417070/article/details/121900909)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [JDBC封装工具类操作数据库(终极版)](https://blog.csdn.net/m0_57606273/article/details/120922107)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [JavaWeb基础之JdbcUtils工具类final](https://blog.csdn.net/weixin_30727835/article/details/96386006)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

PinHsin

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

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

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

打赏作者

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

抵扣说明:

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

余额充值