jdbc 데이터베이스 연결 탱크
주: 어떤 자바 류 는 JDK 에 없 는 것 입 니 다. 오 세 요.http://www.findjar.com/index.x 해당 jar 패키지 찾기
1. 데이터베이스 프로필 (프로젝트 의 classpath 아래)
database.properties
## oracle ##
#c3p0.driver=oracle.jdbc.driver.OracleDriver
#c3p0.url=jdbc:oracle:thin:@192.168.1.49:1523:DB02
## DB2 ##
c3p0.driver=com.ibm.db2.jcc.DB2Driver
c3p0.url=jdbc:db2://172.20.15.174:50000/test
c3p0.user=admin
c3p0.password=admin
c3p0.initialPoolSize=15
#
c3p0.maxPoolSize=20
#
c3p0.minPoolSize=10
# ,n 。 0
c3p0.maxIdleTime=60
# ( )
c3p0.acquireRetryDelay=1000
# c3p0
c3p0.acquireIncrement=15
#
c3p0.acquireRetryAttempts=30
#
c3p0.autoCommitOnClose=false
# statements
c3p0.maxStatementsPerConnection=100
#
c3p0.numHelperThreads=10
### DPCP ###
# , ,
dpcp.maxwait=60000
2. 파일 분석 클래스 설정
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import org.apache.log4j.Logger;
/**
* @ClassName: ParsePropertiesFile
* @Description: (*.properties)
* @author
* @company
* @date 2012-11-8
* @version V1.0
*/
public final class ParsePropertiesFile {
private static final Logger LOG = Logger
.getLogger(ParsePropertiesFile.class);
private static final ParsePropertiesFile instance = new ParsePropertiesFile();
private ParsePropertiesFile() {
}
public static ParsePropertiesFile getInstance() {
return instance;
}
/**
* @Title: getConfig
* @Description: (*.properties)
* @param propFile
*
* @return:Map
* @author
* @date 2012-11-8
*/
public Map getConfig(String propFile) {
InputStream is = null;
try {
is = this.getClass().getClassLoader().getResourceAsStream(propFile);
Properties prop = new Properties();
prop.load(is);
Set> set = prop.entrySet();
Iterator> it = set.iterator();
String key = null, value = null;
Entry
3. IOUtil
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import org.apache.log4j.Logger;
public final class IOUtil {
private static final Logger LOG = Logger.getLogger(IOUtil.class);
private IOUtil() {
}
public static void closeReader(Reader reader) {
if (null != reader) {
try {
reader.close();
reader = null;
} catch (IOException e) {
LOG.error("close reader faile!", e);
}
}
}
public static void closeStream(InputStream is, OutputStream os) {
if (null != is) {
try {
is.close();
is = null;
} catch (IOException e) {
LOG.error("close InputStream fail!", e);
}
}
if (null != os) {
try {
os.close();
os = null;
} catch (IOException e) {
LOG.error("close OutputStream fail!", e);
}
}
}
}
4. CommonConstants
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @ClassName: CommonConstants
* @Description:
* @author wenjianhai
* @company
* @date 2012-11-8
* @version V1.0
*/
public final class CommonConstants {
private CommonConstants() {
}
/** (*.properties) key-value */
public static Map propMap = new ConcurrentHashMap(16);
}
5. 프로필 초기 화
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.apache.log4j.Logger;
/**
* @ClassName: InitServlet
* @Description:
* @author
* @company
* @date 2012-11-8
* @version V1.0
*/
public class InitServlet extends HttpServlet {
/**
* @Fields serialVersionUID : id
*/
private static final long serialVersionUID = -283273527502774557L;
private static final Logger log = Logger.getLogger(InitServlet.class);
@Override
public void init() throws ServletException {
log.info("Start to init InitServlet.");
//
super.init();
//
ParsePropertiesFile.getInstance().getConfig("database.properties");
log.info("End to init InitServlet.");
}
}
6. 웹. xml 에 servlet 설정
initServlet
cn.com.do1.component.init.InitServlet
2
initServlet
/initServlet
7. 데이터베이스 연결 풀
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Vector;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.lang.time.StopWatch;
import org.apache.log4j.Logger;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* @ClassName: ConnectionPool
* @Description: ,
* @author
* @company
* @date 2012-11-15
* @version V1.0
*/
public final class ConnectionPool {
private Vector pool;
private int poolSize;//
private static final Logger log = Logger.getLogger(ConnectionPool.class);
//
protected static ThreadLocal threadLocalCon = new ThreadLocal();
private static final ConnectionPool instance = new ConnectionPool();
private static DataSource dataSource;
/*
* , , , getInstance() 。
* , 。
*/
private ConnectionPool() {
try {
this.poolSize = Integer.parseInt(CommonConstants.propMap
.get("c3p0.maxPoolSize"));
if (dataSource == null) {
initDataSource();
}
if (null == pool) {
//
pool = new Vector(poolSize);
pool = addConnection(poolSize);
}
} catch (Exception e) {
log.error("Init Connection Pool fail!", e);
}
}
/*
*
*/
public static ConnectionPool getInstance() {
return instance;
}
/*
* 。
*/
public synchronized void release(Connection conn) {
// ( , , , )
try {
conn.setAutoCommit(true);
} catch (SQLException e) {
log.error("set auto commit fail!", e);
} catch (Exception e) {
log.error("set auto commit fail!", e);
}
//
pool.add(conn);
//
threadLocalCon.set(null);
}
/*
*
*/
public Connection getConnection() {
Connection con = threadLocalCon.get();
try {
if (con == null || con.isClosed()) {
while (pool.size() == 0) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
log.error(e);
}
}
synchronized (this) {
con = pool.get(0);
threadLocalCon.set(con);
}
}
} catch (Exception e1) {
log.error("Get Connection fail!", e1);
}
return con;
}
/*
* , num 。
*/
private Vector addConnection(int num) {
StopWatch sw = new StopWatch();
sw.start();
Connection conn = null;
try {
// Class.forName(driverClassName);
for (int i = 0; i < num; i++) {
// conn = DriverManager.getConnection(url, username, password);
conn = dataSource.getConnection();
pool.add(conn);
}
} catch (Exception e) {
log.error("add Connection fail!", e);
}
sw.stop();
log.info("end add connection,the time-consuming is:" + sw.getTime());
return pool;
}
/*
* 。
*/
public synchronized void closePool() {
for (int i = 0; i < pool.size(); i++) {
try {
pool.get(i).close();
} catch (SQLException e) {
log.error("close Connection Pool fail!", e);
} catch (Exception e) {
log.error("close Connection Pool fail!", e);
}
pool.remove(i);
}
}
/*
*
*/
public int getAvailableConnectNumber() {
return pool.size();
}
/**
* @Title: initDataSource
* @Description: , DPCP
* @author
* @date 2012-11-16
*/
public static void initDataSourceDpcp() {
// DPCP
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(CommonConstants.propMap.get("c3p0.driver"));
ds.setUrl(CommonConstants.propMap.get("c3p0.url"));
ds.setUsername(CommonConstants.propMap.get("c3p0.user"));
ds.setPassword(CommonConstants.propMap.get("c3p0.password"));
//
ds.setDefaultAutoCommit(Boolean.parseBoolean(CommonConstants.propMap
.get("c3p0.autoCommitOnClose")));
// , 0 ,
ds.setInitialSize(Integer.parseInt(CommonConstants.propMap
.get("c3p0.initialPoolSize")));
//
ds.setMaxActive(Integer.parseInt(CommonConstants.propMap
.get("c3p0.maxPoolSize")));
// ,
ds.setMinIdle(Integer.parseInt(CommonConstants.propMap
.get("c3p0.minPoolSize")));
// , ,
ds.setMaxWait(Integer.parseInt(CommonConstants.propMap
.get("dpcp.maxwait")));
dataSource = ds;
}
/**
* @Title: initDataSource
* @Description: , C3P0
* @author
* @date 2012-11-16
*/
public static void initDataSource() {
// C3P0
ComboPooledDataSource cpds = new ComboPooledDataSource();
try {
cpds.setDriverClass(CommonConstants.propMap.get("c3p0.driver"));
} catch (Exception e) {
log.error("load driver class fail!", e);
}
cpds.setUser(CommonConstants.propMap.get("c3p0.user"));
cpds.setPassword(CommonConstants.propMap.get("c3p0.password"));
cpds.setJdbcUrl(CommonConstants.propMap.get("c3p0.url"));
// , minPoolSize maxPoolSize 。Default: 3 initialPoolSize
cpds.setInitialPoolSize(Integer.parseInt(CommonConstants.propMap
.get("c3p0.initialPoolSize")));
// 。Default: 15 maxPoolSize
cpds.setMaxPoolSize(Integer.parseInt(CommonConstants.propMap
.get("c3p0.maxPoolSize")));
// 。
cpds.setMinPoolSize(Integer.parseInt(CommonConstants.propMap
.get("c3p0.minPoolSize")));
// 。Default: 1000 acquireRetryDelay
cpds.setAcquireRetryDelay(Integer.parseInt(CommonConstants.propMap
.get("c3p0.acquireRetryDelay")));
// ,60 。 0 。Default: 0 maxIdleTime
cpds.setMaxIdleTime(Integer.parseInt(CommonConstants.propMap
.get("c3p0.maxIdleTime")));
// c3p0 。Default: 3 acquireIncrement
cpds.setAcquireIncrement(Integer.parseInt(CommonConstants.propMap
.get("c3p0.acquireIncrement")));
// 60 。Default: 0 idleConnectionTestPeriod
// cpds.setIdleConnectionTestPeriod(60);
// 。Default: false autoCommitOnClose
cpds.setAutoCommitOnClose(Boolean.parseBoolean(CommonConstants.propMap
.get("c3p0.autoCommitOnClose")));
// maxStatementsPerConnection statements
cpds.setMaxStatementsPerConnection(Integer
.parseInt(CommonConstants.propMap
.get("c3p0.maxStatementsPerConnection")));
// c3p0 , JDBC , .
cpds.setNumHelperThreads(Integer.parseInt(CommonConstants.propMap
.get("c3p0.numHelperThreads")));
// 。Default: 30 acquireRetryAttempts
cpds.setAcquireRetryAttempts(Integer.parseInt(CommonConstants.propMap
.get("c3p0.acquireRetryAttempts")));
// 。 。 : 。Default:
// null preferredTestQuery
// cpds.setPreferredTestQuery("select sysdate from dual");
// 。 true connection
// 。 idleConnectionTestPeriod automaticTestTable
// 。Default: false testConnectionOnCheckout
// cpds.setTestConnectionOnCheckout(true);
// true 。Default: false testConnectionOnCheckin
// cpds.setTestConnectionOnCheckin(true);
// JDBC , PreparedStatements 。 statements connection 。 。 maxStatements maxStatementsPerConnection 0, 。Default:
// 0
// cpds.setMaxStatements(1);
// 。
// , getConnection() 。 true,
// 。Default: false breakAfterAcquireFailure
// cpds.setBreakAfterAcquireFailure(false);
dataSource = cpds;
}
/**
* @Title: beginTransaction
* @Description:
* @param conn
* :
* @author
* @date 2012-11-16
*/
public static void beginTransaction(Connection conn) {
try {
if (conn != null) {
if (conn.getAutoCommit()) {
//
conn.setAutoCommit(false);
}
}
} catch (SQLException e) {
log.error("set auto commit to false fail!", e);
} catch (Exception e) {
log.error("begin Transaction fail!", e);
}
}
/**
* @Title: commitTransaction
* @Description:
* @param conn
* :
* @author
* @date 2012-11-16
*/
public static void commitTransaction(Connection conn) {
try {
if (conn != null) {
if (!conn.getAutoCommit()) {
conn.commit();
}
}
} catch (SQLException e) {
log.error("commit transaction fail!", e);
} catch (Exception e) {
log.error("commit transaction fail!", e);
}
}
/**
* @Title: rollbackTransaction
* @Description:
* @param conn
* :
* @author
* @date 2012-11-16
*/
public static void rollbackTransaction(Connection conn) {
try {
if (conn != null) {
if (!conn.getAutoCommit()) {
conn.rollback();
}
}
} catch (SQLException e) {
log.error("rollback transaction fail!", e);
} catch (Exception e) {
log.error("rollback transaction fail!", e);
}
}
/**
* @Title: resetConnection
* @Description:
* @param conn
* :
* @author
* @date 2012-11-16
*/
public static void resetConnection(Connection conn) {
try {
if (conn != null) {
if (conn.getAutoCommit()) {
conn.setAutoCommit(false);
} else {
conn.setAutoCommit(true);
}
}
} catch (SQLException e) {
log.error("reset transaction fail!", e);
} catch (Exception e) {
log.error("reset transaction fail!", e);
}
}
/**
* @Title: setAutoCommit
* @Description:
* @param conn
*
* @param autoCommit
* :
* @author
* @date 2012-11-16
*/
public static void setAutoCommit(Connection conn, boolean autoCommit) {
if (conn != null) {
try {
conn.setAutoCommit(autoCommit);
} catch (SQLException e) {
log.error("set Auto Commit fail!", e);
} catch (Exception e) {
log.error("set Auto Commit fail!", e);
}
}
}
}
8. 호출 (DAO 층)
/**
* @Title: findExpireNotice
* @Description: 2 、
* @param isAll
* 0: ,1: 2
* @return List
* @throws Exception
* @see cn.com.do1.component.business.licencenotice.dao.ILicencenoticeDAO#findExpireNotice(int)
* @author
*/
@Override
public List findExpireNotice(YcBusinessMessagePO bm, int isAll)
throws Exception {
//
Connection conn = null;
try {
conn = ConnectionPool.getInstance().getConnection();
} catch (Exception e) {
logger.error(" !", e);
throw new Exception(" !");
}
List list = new ArrayList();
String sql = null;
if (0 == isAll) {
//
sql = "select b.license_code,a.CUST_NAME,a.CORPORATION_NAME,"
+ "a.MANAGER,a.MANAGER_TEL "
+ "from rm_cust a,rm_license b where a.cust_id=b.cust_id "
+ " and status='1' and INVALIDATION_DATE<=current date";
} else if (1 == isAll) {
// bm.getWarningLimit()
sql = "select b.license_code,a.CUST_NAME,a.CORPORATION_NAME,"
+ "a.MANAGER,a.MANAGER_TEL "
+ "from rm_cust a,rm_license b where a.cust_id=b.cust_id "
+ " and status='1' "
+ " and INVALIDATION_DATE=(current date + "
+ bm.getWarningLimit() + " days)";
}
logger.info(" 2 、 ,the sql is:\r
" + sql);
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
RmLicense license = null;
while (rs.next()) {
license = new RmLicense();
license.setLicenseCode(rs.getString("license_code"));
license.setCustName(rs.getString("CUST_NAME"));
license.setCorporationName(rs.getString("CORPORATION_NAME"));
license.setManager(rs.getString("MANAGER"));
license.setManagerTel(rs.getString("MANAGER_TEL"));
list.add(license);
}
ps.close();
ConnectionPool.getInstance().release(conn);
return list;
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Java 애플리케이션을 모든 SQL 데이터베이스와 연결그래서 오늘 이 기사를 통해 JDBC를 통해 Java 애플리케이션을 SQL 데이터베이스에 연결하기 위해 작성할 수 있는 각 줄을 설명하는 심층 가이드를 제공하여 그들과 모든 커뮤니티를 도우려고 합니다. JDBC는 J...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.