您的位置:首页 > 运维架构 > Tomcat

tomcat配置mysql数据源

2008-06-15 22:42 302 查看
1、在tomcat admin下面建立数据源,如果是tomcat5.5以上的版本需要去下载admin,地址在我的博客上面(我的数据源名称取的是:mySql/testdb)
2、将数据库驱动拷贝到tomcat5.5/common/lib下面
3,在项目的web.xml下面将以下内容放入
<resource-ref>
  <description>DB Connection</description>
  <res-ref-name>mySql/testdb</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth> 
 </resource-ref>
4,在tomcat下面的/conf/Catalina/localhost建立一个与你的项目同名的(项目.xml)
<?xml version="1.0" encoding="UTF-8"?>
<Context privileged="true">
<ResourceLink
global="mySql/testdb"
name="mySql/testdb"
type="javax.sql.DataSourcer"/>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>

5、建立一个测试文件
<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.*"%>
<%@ page import="javax.naming.*"%>
<%@ page session="false" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title></title>
<%
   DataSource ds = null;
   try{
   InitialContext ctx=new InitialContext();
   ds=(DataSource)ctx.lookup("java:comp/env/mySql/testdb");
   Connection conn = ds.getConnection();
   Statement stmt = conn.createStatement();
   String strSql = " select * from userinfo";
   ResultSet rs = stmt.executeQuery(strSql);
    while(rs.next()){
      out.print(rs.getString(2));                
     }
   }
   catch(Exception ex){
       out.print("dd"+ex.getMessage());
    ex.printStackTrace();
   }
%>
</head>
<body>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息