Tomcat 5.5 配置數據源


配置文件:
<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();
 }



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章