Java reading JDBC connection from XML file

Does anyone have an idea how I can write an XMl file that I will have a JDBC connection (username, password, driver, connection) and then read what xml to connect to db?

+1
source share
4 answers

Here is how you could compile the XML:

<?xml version="1.0" encoding="UTF-8"?> <config> <jdbc> <url>jdbc:mysql://localhost:3306/javabase</url> <driver>com.mysql.jdbc.Driver</driver> <username>java</username> <password>d$7hF_r!9Y</password> </jdbc> </config> 

Assuming it is called config.xml and placed at the root of the classpath, here is an example of how you could load it using JAXP and Xpath :

 InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.xml"); Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(input)); XPath xpath = XPathFactory.newInstance().newXPath(); String url = (String) xpath.compile("//config//jdbc//url").evaluate(document, XPathConstants.STRING); String driver = (String) xpath.compile("//config//jdbc//driver").evaluate(document, XPathConstants.STRING); String username = (String) xpath.compile("//config//jdbc//username").evaluate(document, XPathConstants.STRING); String password = (String) xpath.compile("//config//jdbc//password").evaluate(document, XPathConstants.STRING); // ... 

This is just a pretty verbose one, not a properties file. Here is an example of such a properties file:

  jdbc.url = jdbc: mysql: // localhost: 3306 / javabase
 jdbc.driver = com.mysql.jdbc.Driver
 jdbc.username = java
 jdbc.password = d $ 7hF_r! 9Y

Assuming it is called config.properties and placed at the root of the class path (or its root path has been added to the class path), here you can load it from the class path:

 Properties properties = new Properties(); properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties")); String url = properties.getProperty("jdbc.url"); String driver = properties.getProperty("jdbc.driver"); String username = properties.getProperty("jdbc.username"); String password = properties.getProperty("jdbc.password"); // ... 
+8
source

I often use the Spring Framework to externalize the connection pool configuration and configure the jdbc url.

+1
source

Take a look at commons-configuration . You can read several configuration formats with it.

However, for the database connection properties, I think that for a file with the .properties key is better.

+1
source

You can define your own XML schema, bind it to a Java bean, and parse it through JAXB. Then you just need to call the recipients of your bean to create your connection.

+1
source

Source: https://habr.com/ru/post/1392411/


All Articles