JDBC——jdbcUtils加载配置文件赋值

加载配置文件:Properties对象

对应properties文件处理,开发中也使用Properties(唯一与流有关系的集合(是map),可以读取对象变为集合中Key/Value格式)对象进行。我们将采用加载properties文件获得流,然后使用Properties对象进行处理。

l  JDBCUtils.java中编写代码

public class JDBCUtils {

 

    private static String driver;

    private static String url;

    private static String user;

    private static String password;

    // 静态代码块

    static {

        try {

            // 1 使用Properties处理流

            // 使用load()方法加载指定的流

            Properties props = new Properties();

            Reader is = new FileReader("db.properties");

            props.load(is);

            // 2 使用getProperty(key),通过key获得需要的值,

            driver = props.getProperty("driver");

            url = props.getProperty("url");

            user = props.getProperty("user");

            password = props.getProperty("password");

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

    }

 

    /**

     * 获得连接

     */

    public static Connection getConnection() {

        try {

            // 1 注册驱动

            Class.forName(driver);

            // 2 获得连接

            Connection conn = DriverManager.getConnection(url, user, password);

            return conn;

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

    }

}
原文地址:https://www.cnblogs.com/wy20110919/p/8093423.html