修改server.xml,在<GlobalNamingResources>里加入下面的代碼:

  1. <!--oracle--> ?
  2. <Resource?name="jdbc/oracle"?
  3. auth="Container"?
  4. type="javax.sql.DataSource"?
  5. username="scott"?
  6. password="tiger"?
  7. driverClassName="oracle.jdbc.driver.OracleDriver"?
  8. url="jdbc:oracle:thin:@localhost:1521:hqh"?
  9. maxActive="8"?
  10. maxIdle="4"/> ?
  11. <!--mssql--> ?
  12. <Resource?name="jdbc/mssql"?
  13. auth="Container"?
  14. type="javax.sql.DataSource"?
  15. username="sa"?
  16. password="sa"?
  17. driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver"?
  18. url="jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=OA"?
  19. maxActive="8"?
  20. maxIdle="4"/>?

修改context.xml文件,修改后的代碼:

  1. <!--?The?contents?of?this?file?will?be?loaded?for?each?web?application?--> ?
  2. <Context> ?
  3. ?
  4. <!--?Default?set?of?monitored?resources?--> ?
  5. <WatchedResource>WEB-INF/web.xml</WatchedResource> ?
  6. ?
  7. <!--?Uncomment?this?to?disable?session?persistence?across?Tomcat?restarts?--> ?
  8. <!-- ?
  9. <Manager?pathname=""?/> ?
  10. --> ?
  11. ?
  12. <!--?Uncomment?this?to?enable?Comet?connection?tacking?(provides?events ?
  13. on?session?expiration?as?well?as?webapp?lifecycle)?--> ?
  14. <!-- ?
  15. <Valve?className="org.apache.catalina.valves.CometConnectionManagerValve"?/> ?
  16. --> ?
  17. <ResourceLink ?
  18. name="jdbc/oracle"? ?
  19. type="javax.sql.DataSource"? ?
  20. global="jdbc/oracle"/> ?
  21. <ResourceLink ?
  22. name="jdbc/mssql"? ?
  23. type="javax.sql.DataSource"? ?
  24. global="jdbc/mssql"/> ?
  25. </Context>?

調用代碼:

  1. public?static?Connection?con?=?null; ?
  2. ?
  3. public?static?Connection?getConnection()?{ ?
  4. ?
  5. //通過數據源 ?
  6. try?{ ?
  7. Context?context?=?new?InitialContext(); ?
  8. DataSource?dataSource?=?(DataSource)?context.lookup("java:comp/env/jdbc/oracle"); ?
  9. con?=?dataSource.getConnection(); ?
  10. }?catch?(NamingException?e)?{ ?
  11. e.printStackTrace(); ?
  12. }?catch?(SQLException?e)?{ ?
  13. e.printStackTrace(); ?
  14. } ?
  15. ?
  16. return?con; ?
  17. }?

別忘了把數據庫驅動包放在D:\apache-tomcat-6.0.14\lib下哦!

還有一點值得注意的是,打開連接,不用的時候一定要close!否則可能下次要連接的時候出現“死了”的感覺!

sql服務器配置、官方網站的配置:http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html#Database%20Connection%20Pool%20(DBCP)%20Configurations