📄 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 + -