JavaDB-Utils简化DAO层频繁操作数据库

该博客介绍了如何在Java环境下使用JDBC进行数据库连接管理。通过静态初始化加载配置,实现了数据库连接的静态方法获取和释放,减少了代码重复。同时,详细解释了为何在关闭数据库连接后设置为null,以便于JVM的垃圾回收,提高系统资源利用率。博客强调了静态关键字和JVM知识在优化代码中的重要性。
摘要由CSDN通过智能技术生成

在使用JDBC进行数据持久化层时,频繁的连接和释放数据库操作应该作为一个类文件保存,避免代码的重复

开发环境:IntelliJ IDEA 2021.1.1

public class JdbcUtils {

    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    //从配置文件configuration.properties中初始化常量
    static {

        try{
            //两种加载配置文件方法都行
            InputStream input=JdbcUtils.class.getClassLoader().getResourceAsStream("configuration.properties");
//            InputStream input = new FileInputStream("src/main/resources/configuration.properties");
            Properties properties = new Properties();
            properties.load(input);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * function annotation:
     * 获取数据库连接
     * @return Connection
     */
    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url,username,password);

        return connection;
    }
    /**
     * function annotation:
     * 释放资源
     * @return void
     */
    public static void release( Connection connection, Statement statement) throws SQLException {
        if (statement != null){
            //资源连接关闭
            //避免泄露
            statement.close();
            //GC回收
            //节省内存
            statement = null;
        }
        if (connection != null){
            connection.close();
            connection = null;
        }
    }
    public static void release(ResultSet resultSet, Connection connection, Statement statement) throws SQLException {
        if (resultSet != null){
            resultSet.close();
            resultSet=null;
        }
        release(connection,statement);
    }

}

技术总结:
static value:预加载value
static method() :预加载method(),在调用时,并不需要new来构造才能调用目的方法,直接使用类的目的方法

//未使用static
JdbcUtils util = new JdbUtiles();
util.funtion();
------------------------------------------------------
//使用static关键字
JdbcUtils.funtion();

static {

} :预加载{}里面的操作
具体static原理需要了解JVM

xx.close();
xx=null;

xx.close:目的只为了断开连接,避免资源浪费或者流失
而在后面还赋值为null:目的是为了让JVM的GC回收期回收xx对象在内存中

总结:简单的一个类编写,就用到了JVM的一些知识才能理解,JVM的学习很重要

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值