?? connectionfactoryimpl.java
字號:
package com.sunyard.dataanalyze;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
public class ConnectionFactoryImpl implements ConnectionFactory{
private static Map dbMap = new HashMap();
private static void loadDbs(){
URL xmlFileName = ConnectionFactoryImpl.class.getResource("/dbconn.xml");
//String filePath = System.getProperty("user.dir")+"/dbconn.xml";
String filePath = xmlFileName.getPath();
SAXBuilder builder = new SAXBuilder();
Document doc;
try{
doc = builder.build(new File(filePath));
Element root = doc.getRootElement();
List sonNodes = root.getChildren();
Iterator it = sonNodes.iterator();
while(it.hasNext()){
Connection conn;
Element element = (Element)it.next();
String user = element.getChildText("user");
String passWord = element.getChildText("password");
String driver = element.getChildText("driver");
String url = element.getChildText("url");
String dataSource = element.getChildText("datasource");
String dbName = element.getChildText("dbname");
DataBase db = new DataBase();
db.setName(dbName);
db.setDriver(driver);
db.setPassWord(passWord);
db.setUrl(url);
db.setDataSource(dataSource);
db.setUser(user);
dbMap.put(db.getName(), db);
}
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(JDOMException e){
e.fillInStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
public Connection getConnection(String dbName){
if(dbMap.size() == 0){
loadDbs();
}
DataBase db = (DataBase)dbMap.get(dbName);
Connection conn = null;
if(!db.getDataSource().equals("")){
Context context;
try {
context = new InitialContext();
DataSource dataSource = (DataSource)context.lookup(db.getDataSource());
conn = dataSource.getConnection();
} catch (NamingException e) {
e.printStackTrace();
} catch(SQLException e){
e.printStackTrace();
}
}else{
try{
Class.forName(db.getDriver());
conn = DriverManager.getConnection(db.getUrl(), db.getUser(), db.getPassWord());
}catch(SQLException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
return conn;
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -