java - 使用 xml 文件连接到数据库 - java
问题描述
public static JdbcTemplate connectBDD() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:8080/test");
ds.setUsername("root");
ds.setPassword("root");
JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
jdbcTemplate.setDataSource(ds);
return jdbcTemplate;
}
多亏了这些代码行,我才能对我的数据库进行查询。
我见过很多人使用包含连接数据库的所有信息的 xml 文件做同样的事情。
有人可以告诉我如何编写这样的文件,最重要的是如何在 java 代码中调用它。
谢谢 !
解决方案
如果只是你不想让你的用户名/密码硬编码,你可能想从属性文件中读取它:
public static PropertyResourceBundle getProperties(final String fileName)
throws FileNotFoundException, IOException {
try (FileInputStream fis = new FileInputStream(fileName)) {
return new PropertyResourceBundle(fis);
}
}
public static JdbcTemplate connectBDD() throws FileNotFoundException, IOException {
PropertyResourceBundle properties = getProperties("c:\\temp\\testapp.properties");
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:8080/test");
String userName = properties.getString("userName");
ds.setUsername(userName);
String password = properties.getString("password");
ds.setPassword(password);
JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
jdbcTemplate.setDataSource(ds);
return jdbcTemplate;
}
使用 c:\temp\testapp.properties 读取
userName=testUserWithNeededPrivelegesOnly
password=hardToGuessPassword
推荐阅读
- vb.net - TcpClient.Client.Send() 和 TcpClient.GetStream.Write() 是否等效?
- javascript - 如何在每次页面刷新时运行对 Unsplash 的 GET 请求?
- javascript - Cypress new command definition reference
- mvvm - 使用 SwiftUI/Combine,如何避免在 ViewModel 中放置可取消项
- npm - 在 NPM 包中构建 TS 资产的最佳方法是什么
- r - ggplot中的科学记数法
- c - 将文件读入包含 C 中枚举的 typedef 结构?
- r - R函数替换给定范围内的值
- html - 如何使用行对齐来装饰 Bootstrap 网格布局的边距
- amazon-web-services - 如何防止 AWS Lambda 自动从 SQS 队列中删除消息,而是以编程方式将其删除?