1.寻找第三方的数据库java的驱动(如db2的驱动是db2java.zip文件,Oralce的驱动是classes12.zip),并且把它拷贝到Tomcat的库文件目录下。在这里是%TOMCAT_HOME%的commonlib子目录下。注意,一定要把文件变成.jar文件,再拷过来。否则可能出现认不出驱动的问题。
2.配置%TOMCAT_HOME%的conf下的server.xml文件。在Host分支下,删除不必要的Context(如最初安装可能装了Example等,注释掉相关描述)。加入自己的Context,以下是一个附有注释说明的例子:
<!-- 自己的Context,名称叫做GAP -->
reloadable="true" crossContext="true">
<!-- 日志,在%TOMCAT_HOME%的logs下生成localhost_GAP_log.txt日志文件 -->
prefix="localhost_GAP_log." suffix=".txt"
timestamp="true"/>
home="com.wombat.empl.EmployeeRecordHome"
remote="com.wombat.empl.EmployeeRecord"/>
<!-- 数据源名称,可以通过java:/comp/env/jdbc/oracle调用(连接池) -->
<!-- If you wanted the examples app to be able to edit the
user database, you would uncomment the following entry.
Of course, you would want to enable security on the
application as well, so this is not done by default!
The database object could be accessed like this:
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
UserDatabase database =
(UserDatabase) envCtx.lookup("userDatabase");
-->
type="javax.sql.DataSource"/>
<!-- 数据源参数表 -->
<!-- 数据源工厂,通过它得到DataSource -->
factory
org.apache.commons.dbcp.BasicDataSourceFactory
<!-- ORACLE 驱动的类名称 -->
driverClassName
oracle.jdbc.driver.OracleDriver
<!-- jdbc连接的url名称à
url
jdbc:oracle:thin:@192.168.1.11:1521:ODAS
username
system
password
odas
maxActive
50
maxIdle
10
maxWait
-1
type="javax.sql.DataSource"/>
factory
org.apache.commons.dbcp.BasicDataSourceFactory
driverClassName
COM.ibm.db2.jdbc.app.DB2Driver
url
jdbc:db2:WST_DB
username
db2admin
password
123456789
maxActive
50
maxIdle
10
maxWait
-1
3.在相应用到该连接池的Web-app(部署好的web应用,一般在%TOMCAT_HOME%的webapps目录下,也可以通过编辑server.xml来改变,下同)的WEB-INF下面修改web.xm l,在web-app分支内加入数据源
Oracle Connectiong Pool
jdbc/oracle
javax.sql.DataSource
Container
Oracle Connectiong Pool
jdbc/DB2
javax.sql.DataSource
Container
测试及调用方法
Connection conn=null;
Statement stmt =null;
ResultSet rs=null;
try{
Context initContext = new InitialContext();
Context envContext=(Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/DB2");
conn = ds.getConnection();
if(conn!=null){
System.out.println("create connection sucess!");
stmt = conn.createStatement();
if(stmt!=null){
System.out.println("create stmt sucess!");
rs=stmt.executeQuery("select * from WST_TB_CITY");
while(rs.next()){
out.println(rs.getString("CITYNAME")+"
");
}
}else{
System.out.println("create stmt fail!");
}
}else{
System.out.println("create stmt fail!");
}
}catch(Exception e){
System.out.println(e);
}
finally{
if(rs!=null)
rs.close();
if(stmt!=null)
rs.close();
if(conn!=null)
conn.close();
}
%>
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/10294527/viewspace-122418/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/10294527/viewspace-122418/