You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何将MySQL连接凭据迁移至配置文件存储?

将MySQL连接凭据移至配置文件并读取的实现方法

一、创建.properties配置文件

在项目资源目录下(Maven/Gradle项目放src/main/resources,普通Java项目放src目录)创建db.properties文件,写入数据库连接信息:

db.url=jdbc:mysql://path
db.username=xxx
db.password=yyy

二、编写Java代码读取配置并建立连接

用Java原生Properties类加载配置文件,读取凭据后完成数据库操作,同时通过try-with-resources自动管理资源(避免手动关闭引发的异常和资源泄漏):

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
import java.io.InputStream;

public class DBConnection {
    public static void main(String[] args) {
        Properties dbProps = new Properties();
        // 加载配置文件
        try (InputStream inputStream = DBConnection.class.getClassLoader().getResourceAsStream("db.properties")) {
            if (inputStream == null) {
                System.out.println("无法找到db.properties配置文件");
                return;
            }
            dbProps.load(inputStream);

            // 读取配置项
            String url = dbProps.getProperty("db.url");
            String username = dbProps.getProperty("db.username");
            String password = dbProps.getProperty("db.password");

            // 建立连接并执行查询
            try (Connection conn = DriverManager.getConnection(url, username, password);
                 Statement stmt = conn.createStatement();
                 ResultSet rs = stmt.executeQuery("select * from employee")) {

                while (rs.next()) {
                    System.out.println(
                            "Id: " + rs.getInt(1) +
                            ", Name: " + rs.getString(2) +
                            ", Email: " + rs.getString(3));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

关键说明

  • 资源自动管理:try-with-resources语法会在代码块结束后自动关闭Connection、Statement、ResultSet,无需手动调用close()。
  • 配置文件路径:确保配置文件处于项目类路径下,这样getClassLoader().getResourceAsStream()才能正确读取。
  • 敏感信息保护:不要将含账号密码的配置文件提交到公共版本控制系统(如Git),可在.gitignore中添加db.properties规则。

内容的提问来源于stack exchange,提问作者DocJ457

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 21:48:14