JDBCUtils代码

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

public class JDBCUtils {
private static String url;
private static String user;
private static String password;
private static String driver;

static {//读取资源文件
    
    try {
        //获取src路径下的文件----类加载器
        ClassLoader classLoader = JDBCUtils.class.getClassLoader();
        URL res = classLoader.getResource("jdbc.properties");
        String path = res.getPath();
        //1.创建Properties集合类
        Properties p = new Properties();
        //2.加载文件
        p.load(new FileReader(path));
        //3.获取数据,赋值
        url = p.getProperty("url");
        user = p.getProperty("user");
        password = p.getProperty("password");
        driver = p.getProperty("driver");
        //注册驱动
        Class.forName(driver);
    } catch (Exception e) {
        e.printStackTrace();
    } 

}

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

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

}

你可能感兴趣的:(Java基础)