java - 从 context.xml 文件获取数据库凭据

标签 java mysql eclipse

我有一个在 Eclipse 中实现一些 API 的 java 项目。

我有 db.java 文件,可以与 MySQL 数据库进行通信。

我不想将 MySQL 凭据放在 java 文件中,而是将它们放在 /META-INF/context.xml 文件中。

你知道怎么做吗?

这是我当前的代码:

public class db {

    private String userName = null;
    private String password = null;
    private String dbName = null;
    private String db_connect_string = null;

    public db() {
        this.db_connect_string = "jdbc:mysql://localhost/mydb";
        this.dbName = "name";
        this.userName = "uname";
        this.password = "pass";
    }

protected Connection getDBMySQLCon() {
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        return DriverManager.getConnection(this.db_connect_string+"?useSSL=false",  this.userName, this.password);
    } catch (ClassNotFoundException | SQLException | InstantiationException | IllegalAccessException e) {
        e.printStackTrace();
    }
    return null;
}

最佳答案

您可以使用包含所需信息的属性文件来代替 XML 文件。 XML 文件的问题是您必须选择一个 XML 解析器并使用它。

如果您想继续使用属性文件,您可以考虑以下代码片段。

public void setProp() throws Exception{  
    FileReader reader=new FileReader("db.properties");  
    Properties p=new Properties();  
    p.load(reader);  
    // you can get values you want as properties using
    this.db_connect_string = p.getProperty("db_connect_string");  
    this.dbName = p.getProperty("dbName");  
}  

你的文件结构应该是这样的

db_connect_string=connection.string  
dbName=name
userName=uname
password=pass

关于java - 从 context.xml 文件获取数据库凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47888047/

相关文章:

java - 在 Eclipse 或 IBM RAD 中配置作业

java - 如何在java中将调整大小 slider 添加到矩形形状?

java - 双重比较。不同结果的解释

java - webflow测试,找不到流量模型

php - 将字符串拆分为数组 [PHP]

c# - Entity Framework 6 和 MySQL,模型优先

java - 为什么我会收到 NotSerializedException?

java - Firebase Android 读取数据 -> 处理 -> 更新数据 "Global variable problem"

python - 使用 Python 进行 SQL 注入(inject) (WordPress)

java - 在 Java 类中访问 BIRT 数据集的数据