首页 > 解决方案 > 使用 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 代码中调用它。

谢谢 !

标签: javaxmljdbcjdbctemplate

解决方案


如果只是你不想让你的用户名/密码硬编码,你可能想从属性文件中读取它:

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

推荐阅读