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代码中调用它。
谢谢!
答案 0 :(得分:0)
如果只是不想对用户名/密码进行硬编码,则可能需要从属性文件中读取它:
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