java从XML文件读取JDBC连接 [英] java read JDBC connection from XML file

查看:214
本文介绍了java从XML文件读取JDBC连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都知道如何编写XMl文件,我将在其中连接JDBC(用户名,密码,驱动程序,连接),然后读取xml以连接到db?

Anyone have idea how can i write XMl file that i will have JDBC connection (username, passwd, driver, connection) in it and then read that xml for connecting to db?

推荐答案

以下是编写XML的方法:

Here's how you could compose 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>

假设它被称为 config.xml 并且被放置在类路径的根目录中,这是一个如何在JAXP和的帮助下加载它的示例Xpath

Assuming that it's called config.xml and is been placed in the root of the classpath, here's an example how you could load it with help of 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);
// ...

与属性文件相比,它只是非常冗长。以下是此类属性文件的示例:

It's only pretty verbose as opposed to properties files. Here's 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

假设它被命名为 config.properties 并且被放置在类路径的根目录中(或者它的根路径被添加到类路径中),这里是如何你可以从类路径加载它:

Assuming that it's named config.properties and is been placed in the root of the classpath (or its root path is been added to the classpath), here's how you could load it from the classpath:

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");
// ...

这篇关于java从XML文件读取JDBC连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆