配置文件:
<Context path="/apple" docBase="D:\workspace\bolg\webdoc"
privileged="true" antiResourceLocking="false" antiJARLocking="false">
<Resource name="jdbc/blogdb" auth="Container"
type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password=""
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/blogdb?autoReconnect=true"/>
</Context>
调用方式:
Context ctx = null ;
Connection conn = null;
Statement stmt = null ;
ResultSet rs = null;
try{
ctx = new InitialContext();
if( ctx == null) throw new Exception("没有匹配的环境!");
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/blogdb");
if( ds == null ) throw new Exception("没有匹配的数据库!");
conn = ds.getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(" select * from tbl_blog");
while(rs.next()){
out.print(rs.getString(2));
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(rs!=null) rs.close();
if(stmt!=null) stmt.close();
if(conn!=null) conn.close();
if(ctx!=null) ctx.close();
}