修改server.xml,在<GlobalNamingResources>里加入下面的代碼:
- <!--oracle--> ?
- <Resource?name="jdbc/oracle"?
- auth="Container"?
- type="javax.sql.DataSource"?
- username="scott"?
- password="tiger"?
- driverClassName="oracle.jdbc.driver.OracleDriver"?
- url="jdbc:oracle:thin:@localhost:1521:hqh"?
- maxActive="8"?
- maxIdle="4"/> ?
- <!--mssql--> ?
- <Resource?name="jdbc/mssql"?
- auth="Container"?
- type="javax.sql.DataSource"?
- username="sa"?
- password="sa"?
- driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver"?
- url="jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=OA"?
- maxActive="8"?
- maxIdle="4"/>?
修改context.xml文件,修改后的代碼:
- <!--?The?contents?of?this?file?will?be?loaded?for?each?web?application?--> ?
- <Context> ?
- ?
- <!--?Default?set?of?monitored?resources?--> ?
- <WatchedResource>WEB-INF/web.xml</WatchedResource> ?
- ?
- <!--?Uncomment?this?to?disable?session?persistence?across?Tomcat?restarts?--> ?
- <!-- ?
- <Manager?pathname=""?/> ?
- --> ?
- ?
- <!--?Uncomment?this?to?enable?Comet?connection?tacking?(provides?events ?
- on?session?expiration?as?well?as?webapp?lifecycle)?--> ?
- <!-- ?
- <Valve?className="org.apache.catalina.valves.CometConnectionManagerValve"?/> ?
- --> ?
- <ResourceLink ?
- name="jdbc/oracle"? ?
- type="javax.sql.DataSource"? ?
- global="jdbc/oracle"/> ?
- <ResourceLink ?
- name="jdbc/mssql"? ?
- type="javax.sql.DataSource"? ?
- global="jdbc/mssql"/> ?
- </Context>?
調用代碼:
- public?static?Connection?con?=?null; ?
- ?
- public?static?Connection?getConnection()?{ ?
- ?
- //通過數據源 ?
- try?{ ?
- Context?context?=?new?InitialContext(); ?
- DataSource?dataSource?=?(DataSource)?context.lookup("java:comp/env/jdbc/oracle"); ?
- con?=?dataSource.getConnection(); ?
- }?catch?(NamingException?e)?{ ?
- e.printStackTrace(); ?
- }?catch?(SQLException?e)?{ ?
- e.printStackTrace(); ?
- } ?
- ?
- return?con; ?
- }?
別忘了把數據庫驅動包放在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