JDBC工具类的抽取

  • 配置文件(在src下创建config.properties)

    driverClass=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/db14
    username=root
    password=itheima

  • 工具类

    /*
        JDBC工具类
     */
    public class JDBCUtils {
        //1.私有构造方法
        private JDBCUtils(){};
    
        //2.声明配置信息变量
        private static String driverClass;
        private static String url;
        private static String username;
        private static String password;
        private static Connection con;
    
        //3.静态代码块中实现加载配置文件和注册驱动
        static{
            try{
                //通过类加载器返回配置文件的字节流
                InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("config.properties");
    
                //创建Properties集合,加载流对象的信息
                Properties prop = new Properties();
                prop.load(is);
    
                //获取信息为变量赋值
                driverClass = prop.getProperty("driverClass");
                url = prop.getProperty("url");
                username = prop.getProperty("username");
                password = prop.getProperty("password");
    
                //注册驱动
                Class.forName(driverClass);
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        //4.获取数据库连接的方法
        public static Connection getConnection() {
            try {
                con = DriverManager.getConnection(url,username,password);
            } catch (SQLException e) {
                e.printStackTrace();
            }
    
            return con;
        }
    
        //5.释放资源的方法
        public static void close(Connection con, Statement stat, ResultSet rs) {
            if(con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
    
            if(stat != null) {
                try {
                    stat.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
    
            if(rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    
        public static void close(Connection con, Statement stat) {
            close(con,stat,null);
        }
    }

 注:本章博客是对上篇博客所做的一个功能优化。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

悠然予夏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值