JDBC开发中需要连接到不同的数据库,利用XML文件保存不同类型
数据库的连接参数,并使用统一的程序解析XML以取得相应的连接参数。
[
java]
<<Db.xml>>
<?xml version="1.0" encoding="UTF-8"?>
<DBS>
<DB>
<type>Oracle</type>
<driver>oracle.jdbc.driver.OracleDriver</driver>
<url>jdbc:oracle:thin:@localhost:1521:goudan</url>
<user>pubuser1</user>
<pass
word>11111111</pass
word>
</DB>
<DB>
<type>mysql</type>
<driver>org.git.mm.mysql.Driver</driver>
<url>jdbc:mysql://localhost:3306/BookDB</url>
<user>pubuser2</user>
<pass
word>11111111</pass
word>
</DB>
<DB>
<type>sqlserver</type> <driver>com.microsoft.jdbc.sqlserver.SQLServerDriver</driver>
<url>jdbc:Microsoftqlserver://127.0.0.1:1433</url>
<user>pubuser3</user>
<pass
word>11111111</pass
word>
</DB>
</DBS>
<<DBTest.
java>>
package test.xml;
import
java.io.IOException;
import
javax.xml.parsers.DocumentBuilder;
import
javax.xml.parsers.DocumentBuilderFactory;
import
javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class DBTest {
public DBTest(String type) {
// this.type = type ;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();// 创建解析器
Document doc = db.parse("Db.xml");// 解析地址
NodeList n1 = doc.getElementsByTagName("DB");// 得到含有DB标签的一个列表
for (int i = 0; i < n1.getLength(); i++) {
Element myNode = (Element) n1.item(i);// 通过item方法获得每个对象
if (myNode.getElementsByTagName("type").item(0).getFirstChild()
.getNodeValue().equals(type)) {
String driver = myNode.getElementsByTagName("driver").item(
0).getFirstChild().getNodeValue();
String url = myNode.getElementsByTagName("url").item(0)
.getFirstChild().getNodeValue();
String user = myNode.getElementsByTagName("user").item(0)
.getFirstChild().getNodeValue();
String pass
word = myNode.getElementsByTagName("pass
word")
.item(0).getFirstChild().getNodeValue();
System.out.println(driver + " " + url + " " + user + " "
+ pass
word);
break;
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] rag) {
DBTest dbt1 = new DBTest("Oracle");
DBTest dbt2 = new DBTest("mysql");
DBTest dbt3 = new DBTest("sqlserver");
}
}