서블릿 JSP
JSP DB연동하기, 커넥션 풀(DBCP)
짱코딩러
2022. 9. 30. 21:40
[1] ojdbc.jar 파일을 적용 해 준다.
(DBCP 라이브러리)
[2] 이 방법은 일회성임 이렇게 하면 서버 새로 켤때마다 server에 Resource태그달아서 붙여줘야됩니다
Servers/Tomcat/server.xml
https://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html
<Resource name="jdbc/myoracle" auth="Container"
type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:@127.0.0.1:1521:mysid"
username="scott" password="tiger" maxActive="20" maxIdle="10"
maxWait="-1"/>
[2] 이렇게 입력해주자!
WEB-INF/web.xml
해당 resource를 참조한다는 선언.
<resource-ref>
<description>DBCP</description>
<res-ref-name>jdbc/myOracle</res-ref-name>
<res-type>javax.sql.dataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
META-INF/context.xml
<context>
<Resource auth="Container"
driverClassName="oracle.jdbc.OracleDriver" maxIdle="10" maxTotal="20"
maxWaitMillis="-1" name="jdbc/myoracle" password="1234"
type="javax.sql.DataSource" url="jdbc:oracle:thin:@127.0.0.1:1521:XE"
username="wine" />
</context>
[3] DBManager.java
public class DBManager {
public static Connection getConnection() throws Exception {
// 그릇을 만들고
Context initContext = new InitialContext();
// 환경을 찾어(컨테이너에 등록된 정보)
Context envContext = (Context) initContext.lookup("java:/comp/env");
// 어떤정보냐면 마이오라클을 찾어
DataSource ds = (DataSource) envContext.lookup("jdbc/myoracle");
// 찾았으면 연결해주자(컨넥션풀이랑 연결)
Connection conn = ds.getConnection();
System.out.println("Conn 성공!");
return conn;
}
public static void close(Connection conn, PreparedStatement pstmt,
ResultSet rset) {
if (rset != null) {
try {
rset.close();
} catch (SQLException e) {
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
}
public static void close(Connection conn, PreparedStatement pstmt) {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
}
}