栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

在使用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();
        }
    }
    
    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url,username,password);

        return connection;
    }
    
    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的学习很重要

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/885119.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号