标签:
两种方式,图形化和字符型配置,图形化需要部署一个应用,字符型配置如下:
需要文件
mysql-connector-java-5.1.16-bin.jar
Oracle需要classes12.jar文件拷贝到$CATALINA_HOME/lib下面.
在Tomcat的Server.xml,找到需要采用数据池的Context一段,加入Resource内容,配置内容如下:
<Resource name="jdbc/TestJavaWeb"
auth="Container"
type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="oracle"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mysql?autoReconnect=true"
factory = "org.apache.dbcp.BasicDataSourceFactory"
characterEncoding="utf-8">
</Resource>
如果是Oracle,需要
<Context path="/DataSource" reloadable="true" docBase="E:\Program\Programs\DataSource" workDir="E:\Program\Programs\DataSource\work" >
<Resource name="jdbc/myoracle" auth="Container"
type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:@192.168.104.173:1521:orcl"
username="system" password="manager" maxActive="20" maxIdle="10"
maxWait="-1"/>
</Context>
在Web程序的web.xml文件中配置数据源引用。配置代码如下:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestJavaWeb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
获取数据源连接对象,获取代码如下:
/**
* 获得数据源
*
* @return
* @throws NamingException
* @throws SQLException
*/
public Connection getConnection() throws NamingException, SQLException {
Connection conn = null;
Context initContext = new InitialContext(); // 实例化一个InitialContext
Context envContext = (Context) initContext.lookup("java:/comp/env"); // 获取所有的资源
DataSource ds = (DataSource) envContext.lookup("jdbc/TestJavaWeb"); // 获取JNDI数据源
conn = ds.getConnection();
return conn;
}
jsp文件主要测试代码如下:
<%@page import="java.sql.*"%>
<%@page import="javax.sql.DataSource"%>
<%@page import="javax.naming.*"%>
<%
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx
.lookup("java:comp/env/jdbc/TestJavaWeb");
Connection conn = ds.getConnection();
Statement state = conn.createStatement();
String sql = "select user from user";
ResultSet rs = state.executeQuery(sql);
while (rs.next()) {
out.println(rs.getString(1) + "--<tr>");
out.println(rs.getString(1) + "--<tr>");
out.println(rs.getString(1) + "<br>");
}
rs.close();
state.close();
conn.close();
%>
标签:
原文地址:http://www.cnblogs.com/ericnie/p/5208137.html