Java连接数据库JDBC-类加载方式

上一篇文章我们说到了JDBC连接数据的方式有一个properties的方式,这里我们介绍一下用过加载类的方式,在用properties对象的方式,伪代码如下

static{
        try {
            // 1.通过当前类获取类加载器
        ClassLoader classLoader=JDBCDemo3.class.getClassLoader();
            // 2.通过类加载器的方法获得一个输入流
        InputStream is=classLoader.getResourceAsStream("DB.properties");
            // 3.创建一个properties对象
        Properties bundle=new Properties();
            // 4.加载输入流
            bundle.load(is);
            // 5.获取相关参数的值
            driver = bundle.getProperty("driver.name");
            jdbcurl = bundle.getProperty("jdbcurl");
            username = bundle.getProperty("username");
            password = bundle.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

猜你喜欢

转载自blog.csdn.net/paicmis/article/details/79955432