我有一个在 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/