Tomcat 7.0 连接 mysql5.0

1,mysql-connector-java-5.0.4-bin.jar  放入到  C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib

2,项目的web.xml与tomcat一致



        webt3
        
                index.jsp
        
        
                Tomcat 7 DBCP
                jdbc/mysql5
                javax.sql.DataSource
                Container
        
3,tomcat/conj中的context.xml






    
    WEB-INF/web.xml

    
    

    
    

     


4,测试:index.jsp

<%@ page language="java" contentType="text/html; 

charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*, javax.sql.*, javax.naming.*" %>





Insert title here


<%
Connection conn=null;
PreparedStatement stmt=null;
ResultSet rs=null;

String sql=null;
String username=null;
String alias=null;
String pwd=null;
String strMsg=null;
try{
    Context cxt = new InitialContext();
    DataSource ds = (DataSource)cxt.lookup

("java:/comp/env/jdbc/mysql5");
    conn = ds.getConnection();
    sql="SELECT 1 ";
    stmt=conn.prepareStatement(sql);
    rs=stmt.executeQuery(sql);
    if( rs.next() ){
        strMsg="连接ok";

        out.println("连接ok");
    }else{
        out.println("rs.next() fail");
    }
    rs.close();
    
} catch(Exception e){
    out.println("连接失败:"+e.getMessage());
    //e.printStackTrace();
}

try{
    if(stmt!=null) stmt.close();
}catch(Exception e){}

try{
    if(conn!=null) conn.close();
}catch(Exception e){}


%>



OK,

则成功



你可能感兴趣的:(Tomcat 7.0 连接 mysql5.0)