?? connectionfactory.java
字號:
package com.insit.intranet.common.db;
import java.sql.*;
import javax.sql.*;
import java.util.*;
import java.io.*;
import javax.naming.*;
/**
* 獲得數據庫連接connection
* @author ypb
* 數據庫聯接池 = 工廠模式 + 單件模式的組合
*/
public class ConnectionFactory {
private String driver = null;
private String dbUrl = null;
private String userName = null;
private String password = null;
private String contextFactory = null;
private String serviceProvider= null;
private static ConnectionFactory factory = null;
synchronized public static ConnectionFactory getFactory() throws IOException {
if (factory == null) {
factory = new ConnectionFactory();
}
return factory;
}
private ConnectionFactory() throws IOException {
init();
}
private void init(){
InputStream is = getFileInputStream();
Properties props = new Properties();
try{
props.load(is);
driver = props.getProperty("driver_name");
dbUrl = props.getProperty("db_url");
userName = props.getProperty("user_name");
password = props.getProperty("password");
contextFactory = props.getProperty("context_factory");
serviceProvider = props.getProperty("service_provide_url");
}catch(Exception e){
e.printStackTrace();
}
}
private InputStream getFileInputStream() {
InputStream is = getClass().getResourceAsStream("db_config.properties");
return is;
}
public Connection getConnection() throws SQLException,ClassNotFoundException {
Class.forName(driver);
return DriverManager.getConnection(dbUrl, userName, password);
}
/**
* 通過jndi獲取數據庫連接
* @param jndiName
* @return
* @throws NamingException
* @throws SQLException
*/
public Connection getConnection(String jndiName)throws NamingException,SQLException{
Properties myProperties = new Properties();
myProperties.setProperty(Context.INITIAL_CONTEXT_FACTORY,contextFactory);
myProperties.setProperty(Context.PROVIDER_URL,serviceProvider);
Context ctx = new InitialContext(myProperties);
DataSource ds = (DataSource)ctx.lookup(jndiName);
Connection conn = ds.getConnection();
return conn;
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -