JNDI配置資料庫連線池

笨笨鼠→_→發表於2012-07-06


1.配置tomcat中conf目錄下的context.xml檔案

<Resource name = "jdbc/ds"
     auth = "Container"
     type = "javax.sql.DataSource"
     maxActive = "100"
     maxIdle = "30"
     maxWait = "10000"
     username = "sa"
     password = "123456a"
     driverClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
     url = "jdbc:sqlserver://localhost:1433;databaseName=QQDB;"
 />

2.得到資料來源

 javax.naming.Context ctx = null;
  DataSource ds = null;
  try {
   ctx = new javax.naming.InitialContext();
   ds = (DataSource)ctx.lookup("java:comp/env/jdbc/ds");
   System.out.println("資料來源:"+ds);
  } catch (NamingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

3.注意:由於JNDI資料來源是由web容器驅動的,所以要將 資料庫驅動Copy到tomcat中的lib目錄下,
       
      並且只能在web頁面下訪問才有效,不能進行區域性測試(有待改進)

 

測試JNDI配置資料庫連線池(Action)

package com.wang.owbHome.web.action;
import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.jstl.sql.Result;
import javax.sql.DataSource;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.wang.owbHome.business.util.DB;


public class TestDataSourceAction extends Action {

 public ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {
   //TODO 測試資料連線池程式碼
  javax.naming.Context ctx = null;
  DataSource ds = null;
  try {
   ctx = new javax.naming.InitialContext();
   ds = (DataSource)ctx.lookup("java:comp/env/jdbc/ds");
   System.out.println("資料來源:"+ds);
  } catch (NamingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  Connection conn = ds.getConnection();
  DB db = new DB();
  db.setConnection(conn);
  String sql1 = "select * from QQUser";
  db.setSqlValues(sql1);
  try {
   Result rs = db.executeQuery();
  
   if(rs == null || rs.getRowCount() == 0){
    System.out.println("沒有結果");
   }else{
    System.out.println("共有" + rs.getRowCount() +"個結果!");
   }
   db.closeConn();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println("ni");
  return mapping.findForward("success");
 }
 
}

相關文章