JDBC工具类

package cn.it.JDBCUtils;

import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

/*
    JDBCUtils:JDBC工具类
 */
public class JDBCUtils {
    private static String url;
    private static String user;
    private static String password;
    private static String driver;

    //使用静态代码块读取文件
    static {
        //读取资源文件,获取值:使用properties集合
        //1.创建properties集合
        Properties pro = new Properties();
        try {
            //获取文件绝对路径
            ClassLoader c = JDBCUtils.class.getClassLoader();
            URL resource = c.getResource("jdbc.properties");
            String path = resource.getPath();

            //2.加载文件
            pro.load(new FileReader(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //3.获取数据,赋值
        url = pro.getProperty("url");
        user = pro.getProperty("user");
        password = pro.getProperty("password");
        driver = pro.getProperty("driver");

        //4.获取驱动
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //获取连接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }


    //释放资源
    public static void close(Statement stmt, Connection conn){
        if (stmt != null){
            try {
                stmt.close();
            } catch (SQLException t) {
                t.printStackTrace();
            }
        }
        if (conn != null){
            try {
                conn.close();
            } catch (SQLException t) {
                t.printStackTrace();
            }
        }
    }
    public static void close(ResultSet rs, Statement stmt, Connection conn){
        if (stmt != null){
            try {
                stmt.close();
            } catch (SQLException t) {
                t.printStackTrace();
            }
        }
        if (conn != null){
            try {
                conn.close();
            } catch (SQLException t) {
                t.printStackTrace();
            }
        }
        if (rs != null){
            try {
                rs.close();
            } catch (SQLException t) {
                t.printStackTrace();
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值