ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] # properties配置文件 开发中获得连接的4个参数(驱动、URL、用户名、密码)通常都存在配置文件中,方便后期维护,程序如果需要更换数据库,只需要修改配置文件即可 通常情况下,我们习惯使用properties文件,此文件我们将做如下要求: 1. 文件位置:任意,建议src下 2. 文件名称:任意,扩展名为properties 3. 文件内容:一行一组数据,格式是“key=value”. a) key命名自定义,如果是多个单词,习惯使用点分隔。例如:jdbc.driver b) value值不支持中文,如果需要使用非英文字符,将进行unicode转换。 * 创建配置文件 在项目跟目录下,创建文件,输入“db.properties”文件名。 文件中的内容 ~~~ driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mydb user=root password=root ~~~ * 加载配置文件:Properties对象 对应properties文件处理,开发中也使用Properties对象进行。我们将采用加载properties文件获得流,然后使用Properties对象进行处理。 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); } } } ~~~ ## ResourceBundle 工具 ~~~ //jdk提供的工具类加载properties文件,名字db.properties的后缀可以省略 ResourceBundle bundle = ResourceBundle.getBundle("db"); //通过key获得需要的值 String driver = bundle.getString("driver"); System.out.println(driver); ~~~