簡體   English   中英

使用XML文件連接到數據庫-Java

[英]Connect to a database using xml file - 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM