欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

在Tomcat服务器下使用连接池连接Oracle数据库

程序员文章站 2022-07-20 14:44:40
下面介绍在tomcat服务器下使用连接池来连接数据库的操作 一:修改web.xml文件: 复制代码 代码如下:
下面介绍在tomcat服务器下使用连接池来连接数据库的操作

一:修改web.xml文件:
复制代码 代码如下:

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="webapp_id" version="3.0">
<display-name>project</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>

<resource-ref>
<description>dbconnection</description>
<res-ref-name>siniteksirm</res-ref-name>
<res-type>javax.sql.datasource</res-type>
<res-auth>container</res-auth>
</resource-ref>
</web-app>

在web-app之间插入<resource-ref>这段代码。指定要是用的resource名称。

二:修改tomcat下的context.xml文件:

在context标签之间加入如下代码。
复制代码 代码如下:

<resource name="siniteksirm" auth="container"
type="javax.sql.datasource"
driverclassname="oracle.jdbc.oracledriver"
url="jdbc:oracle:thin:@192.168.1.196:1521:orcl"
username="paxt"
password="paxt"
maxactive="20"
maxidle="10"
maxwait="-1"
testonborrow="true"
validationquery="select 1 from dual"/>

三:选择oracle的数据库驱动,加入到tomcat的lib包中。本项目中为:ojdbc14.jar.

四:提供一个jsp页面:
复制代码 代码如下:

<%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%>
<%@ page import="javax.naming.context" %>
<%@ page import="javax.naming.initialcontext" %>
<%@ page import="java.sql.*" %>
<%@ page import="javax.sql.datasource" %>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>insert title here</title>
</head>
<body>
<%
datasource ds = null;
try{
context context = new initialcontext();
ds = (datasource)context.lookup("java:comp/env/siniteksirm");
connection conn = ds.getconnection();
preparedstatement pst = conn.preparestatement("select * from sdc_fundbase where rownum <= 2");
resultset rs = pst.executequery();
while(rs.next()){
out.println(rs.getstring("fund4"));
out.println("<br/>");
}
if(ds != null){
out.println("数据库连接");
}
}catch(exception e){
e.printstacktrace();
out.println("数据库连接失败");
}
%>
</body>
</html>

启动tomcat,这样就可以访问页面。