[ tomcat ] วิธีใช้ database connection pool (DBCP) จาก JNDI

1. Set up the Tomcat ↔ PostgreSQL side of the connection pool ในไฟล์ web/META-INF/context.xml

<Context path="/hello">
<!-- Link to the local PostgreSQL database -->
<Resource
name="jdbc/postgres"
auth="Container"
type="javax.sql.DataSource"
maxActive="20"
maxIdle="10"
maxWait="5000"
username="tomcat"
password="tomcat"
driverClassName="org.postgresql.Driver"
removeAbandoned="true"
removeAbandonedTimeout="60"
logAbandoned="true"
url="jdbc:postgresql://localhost:5432/tomcat"
validationQuery="select version();"
/>
</Context>

2. ใส่นี่ลงไปในไฟล์ web/WEB-INF/web.xml

ยัดไว้ในแท็ก web-app นะ

<resource-ref>
<description>PostgreSQL Datasource</description>
<res-ref-name>jdbc/postgres</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

3. วิธี pool คือ

import javax.naming.InitialContext;
import java.sql.*;
import javax.sql.*;
...
try {
InitialContext cxt = new InitialContext();
DataSource ds =
(DataSource) cxt.lookup( "java:/comp/env/jdbc/postgres" );
Connection db = ds.getConnection();
PreparedStatement stmt =
db.prepareStatement( "select * from students" );
ResultSet rs = stmt.executeQuery();
writer.println( "<h3>Web nerds:</h3>" );
while ( rs.next() ) {
writer.println( "<p>" + rs.getString( "name" ) +
" is a Web Nerd.</p>" );
}
rs.close();
db.close();
} catch ( javax.naming.NamingException e ) {
writer.println( "<h3>Cannot find PostgreSQL database " +
"connection pool via JNDI!</h3>" );
e.printStackTrace( writer );
} catch ( java.sql.SQLException e ) {
writer.println( "<h3>SQL Exception!</h3>" );
e.printStackTrace( writer );
}

รายละเอียดเพิ่มเติม :

JNDI : http://java.sun.com/javase/6/docs/technotes/guides/jndi/index.html
JNDI tutorial : http://java.sun.com/products/jndi/tutorial/index.html.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s