通过jdbc.properties配置文件实现JDBCUtils工具类

/**
 * 编写数据库连接的工具类,JDBC工具类
 * 获取连接对象采用读取配置文件方式
 * 读取文件获取连接,执行一次,static{}
 * jdbc.properties文件配置 
 * driver=com.mysql.jdbc.Driver
 * url=jdbc:mysql://localhost:3306/day28
 * username=root
 * password=root1234
 */
public class JDBCUtilsConfig {
    private static Connection con;
    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;

    static {
        try {
            readConfig();
            Class.forName(driverClass);
            con = DriverManager.getConnection(url, username, password);
        } catch (Exception ex) {
            throw new RuntimeException("数据库连接失败");
        }
    }

    private static void readConfig() throws Exception {
        //读取jdbc.properties配置文件
        InputStream in = JDBCUtilsConfig.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties pro = new Properties();
        pro.load(in);
        driverClass = pro.getProperty("driverClass");
        url = pro.getProperty("url");
        username = pro.getProperty("username");
        password = pro.getProperty("password");
    }


    public static Connection getConnection() {
        return con;
    }

    public static void close(Connection con, Statement stat) {

        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException ex) {
            }
        }

        if (con != null) {
            try {
                con.close();
            } catch (SQLException ex) {
            }
        }

    }


    public static void close(Connection con, Statement stat, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException ex) {
            }
        }

        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException ex) {
            }
        }

        if (con != null) {
            try {
                con.close();
            } catch (SQLException ex) {
            }
        }

    }

你可能感兴趣的:(通过jdbc.properties配置文件实现JDBCUtils工具类)