美文网首页
通过jdbc.properties配置文件实现JDBCUtils

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

作者: Marlon_IT | 来源:发表于2018-02-01 17:31 被阅读14次
    /**
     * 编写数据库连接的工具类,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

          本文链接:https://www.haomeiwen.com/subject/ctxjzxtx.html