?? dbconfig.java
字號(hào):
/*
* DBConfig.java
*
* Created on 2007年5月12日, 下午1:14
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package utils;
import java.sql.*;
import javax.swing.JOptionPane;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import plugin.*;
/**
*
* @author Virlene Cheng
*/
public class DBConfig implements IDBResource
{
public static final String CONFIG_DB_FILE = "Athena.xml";
public static final String NODE_DATABASE = "database";
public static final String NODE_DRIVER = "driver";
public static final String NODE_URL = "url";
public static final String NODE_USERNAME = "username";
public static final String NODE_PASSWORD = "password";
private String configFile;
private String driver;
private String url;
private String username;
private String password;
/** 構(gòu)造函數(shù) */
public DBConfig()
{
this.configFile = DBConfig.CONFIG_DB_FILE;
loadConfig();
}
/**
* 構(gòu)造函數(shù)
* @param 配置文件
*/
public DBConfig(String configFile)
{
this.configFile = configFile;
loadConfig();
}
/**
* 獲取數(shù)據(jù)庫連接
* @return 數(shù)據(jù)庫連接
*/
public Connection getConnection()
{
Connection conn = null;
try
{
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
}
catch(Exception ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "無法連接數(shù)據(jù)庫,請(qǐng)檢查!", "錯(cuò)誤", JOptionPane.ERROR_MESSAGE);
}
return conn;
}
/**
* 讀取數(shù)據(jù)庫配置
*/
private void loadConfig()
{
try
{
//初始化XML文件讀取器
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(configFile);
Element root = doc.getDocumentElement();
//獲取數(shù)據(jù)庫配置節(jié)點(diǎn)
Node database = root.getElementsByTagName(DBConfig.NODE_DATABASE).item(0);
NodeList list = database.getChildNodes();
//獲取數(shù)據(jù)庫的各項(xiàng)配置
for (int i = 0; i < list.getLength(); i++)
{
Node tempNode = list.item(i);
if (tempNode.getNodeName().equals(DBConfig.NODE_DRIVER))
{
driver = tempNode.getTextContent();
}
if (tempNode.getNodeName().equals(DBConfig.NODE_URL))
{
url = tempNode.getTextContent();
}
if (tempNode.getNodeName().equals(DBConfig.NODE_USERNAME))
{
username = tempNode.getTextContent();
}
if (tempNode.getNodeName().equals(DBConfig.NODE_PASSWORD))
{
password = tempNode.getTextContent();
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "讀取配置文件錯(cuò)誤,請(qǐng)檢查文件的完整性!", "錯(cuò)誤", JOptionPane.ERROR_MESSAGE);
}
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -