我的一亩三分地

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  2 随笔 :: 14 文章 :: 3 评论 :: 0 Trackbacks

以Tomcat 5.5 ,Mysql 5.0为例说明
1 在tomcat的admin页面中设置Data Source

JNDI Name:TEST
Data Source URL:jdbc:mysql://localhost:3306/test
JDBC Driver Class: com.mysql.jdbc.Driver
User Name: test                      <!--数据库的用户名,密码-->
Password:****

2 在tomcat_home/conf/context.xml文件中的<context></context>之间加入下面的代码:

<Resource
      auth="baogenfly"
      description="test"
      name="jdbc/test"
      type="javax.sql.DataSource"
      password="test"
      driverClassName="com.mysql.jdbc.Driver"
      maxWait="5000"
      username="test"
      url="jdbc:mysql://localhost:3306/test"
      maxActive="4"/>

3 在具体的web应用中的WEB-INF目录下的web.xml文件中加入下面的代码:

<resource-ref>
        <description> DataSource example</description>
        <res-ref-name>jdbc/test</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>baogenfly</res-auth>
</resource-ref>

4 测试代码:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="javax.sql.*" %>
<%@ page import="javax.naming.*" %>
<!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=ISO-8859-1">
<title>JNDI TEST</title>
</head>
<body>
<% String path = request.getContextPath();
   String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 
   Connection conn = null;
   PreparedStatement ps = null;
   ResultSet rs = null;
  
   Context initCtx = new InitialContext();
   Context ctx = (Context)initCtx.lookup("java:comp/env");
   DataSource ds = (DataSource) ctx.lookup("jdbc/test");
   conn = ds.getConnection();
   ps = conn.prepareStatement("Select * from balance");
   rs = ps.executeQuery();
   while(rs.next()){
    out.println(rs.getString(1)+"<br>");
    out.println(rs.getString(2)+"<br>");
    out.println(rs.getString(3)+"<br>");
    out.println(rs.getString(4)+"<br>");
   }
   rs.close();
   stmt.close();
%>


</body>
</html>

posted on 2007-01-22 23:23 王某某 阅读(415) 评论(0)  编辑  收藏 所属分类: Web相关

只有注册用户登录后才能发表评论。


网站导航: