jdbc工具类

本文介绍了如何使用Java编写一个工具类,封装数据库连接、资源管理和类加载功能,利用`Class.forName`动态加载JDBC驱动,仅在首次执行时加载,以提高性能。同时展示了getConnection和clo方法,确保资源的正确关闭。
摘要由CSDN通过智能技术生成

工具类的作用:封装加载驱动,获取链接,释放资源

这个工具类包括数据库连接,资源管理,查询操作等功能

类加载时的加载驱动:将class.forName("com.mysql.jdbc.Driver")代码有第一次加载的时候执行一次就不再执行了,只需加载一次,不需重复加载

jdbc工具类代码:

private  static String driver;
private static  String url;
private  static  String username;
private static  String password;
static {
    InputStream is=null;
    try {
        is=jdbcutils.class.getClassLoader().getResourceAsStream("jdbc");
        Properties properties=new Properties();
        properties.load(is);
        driver=properties.getProperty("driver");
        url=properties.getProperty("url");
        password=properties.getProperty("password");
        username=properties.getProperty("username");
        System.out.println(driver);
        System.out.println(password);
        System.out.println(username);
        System.out.println(url);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }finally {
        if (is!=null){
            try {
                is.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
public static Connection getConnection() throws SQLException, ClassNotFoundException {
    Class.forName(driver);
    Connection connection= DriverManager.getConnection(url,password,username);
    return connection;
}
public static void clo(ResultSet resultSet, Statement statement, Connection connection) throws SQLException {
    if (resultSet != null) {
        resultSet.close();
    }
    if (statement != null) {
        statement.close();
    }
    if (connection != null) {
        connection.close();
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值