develog

dbcp test 본문

Dev/Java

dbcp test

냐옴 2013. 3. 1. 00:33

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;


import javax.sql.DataSource;


import org.apache.commons.dbcp.BasicDataSource;



public class TestDbcp {


public static void main(String[] args) {

Logger.info("START");

Logger.info("------------------------------------------------");

Connection conn = null;

PreparedStatement pstmt = null;

ResultSet rs = null;

String sql = null;

try {

conn = getConnection();

sql = new String("SELECT 123 CNT FROM DUAL");

pstmt = conn.prepareStatement(sql);

rs = pstmt.executeQuery();

if (rs.next()) {

System.out.println(rs.getString("CNT"));

}

} catch (Exception e) {

e.printStackTrace();

} finally {

closeStatement(pstmt, rs);

closeConnection(conn);

}

Logger.info("------------------------------------------------");

Logger.info("END");

}

private static Connection getConnection() throws Exception {

return getConnectionDev4();

}

private static Connection getConnectionDev4() throws Exception {

String driverClassName = "oracle.jdbc.driver.OracleDriver";

String url   = "jdbc:oracle:thin:@127.0.0.1:1521:ORCL";

String username   = "scott";

String password   = "tiger";

DataSource ds = getDataSourceTemplate(driverClassName, url, username, password);

return ds.getConnection();

}

private static DataSource getDataSourceTemplate(String driverClassName, String url, String username, String password) {

BasicDataSource ds = null;

try {

ds = new BasicDataSource();

ds.setDriverClassName(driverClassName);

ds.setUrl(url);

ds.setUsername(username);

ds.setPassword(password);

ds.setMaxActive(1);

ds.setMaxIdle(0);

ds.setMinIdle(0);

ds.setMaxWait(1);

} catch (Exception e) {

e.printStackTrace();

}

return ds;

}

public static void closeStatement(PreparedStatement pstmt, ResultSet rs) {

if (rs != null) {

try {

rs.close();

rs = null;

} catch (Exception e) {

}

}

if (pstmt != null) {

try {

pstmt.close();

pstmt = null;

} catch (Exception e) {

}

}

}

public static void closeConnection(Connection conn) {

if (conn != null) {

try {

conn.close();

conn = null;

} catch (Exception e) {

}

}

}

}


'Dev > Java' 카테고리의 다른 글

synchronized  (0) 2013.03.17
jndi test  (0) 2013.03.01
variable arguments  (0) 2013.02.23
XML DOM  (0) 2013.01.27
AES  (0) 2013.01.27
Comments