网上这类文章特别多,此教程是本人实践确保一个正常运行的一个.
1.安装MYSQL TOMCAT
2.copy mysql-connector-java-3.1.11-bin.jar to %TOMCAT_HOME%\common\lib
drop database if exists datasource;
create database datasource;
use datasource;
create table user(
username varchar(50) not null,
password varchar(50),
primary key (username)
);
insert into user(username,password) values("kingbill","10041207");--插入测试数据
3.使用Tomcat的web管理应用配置数据源
3.1 http://127.0.0.1:8080/admin/ enter username password
3.2 Resources->Data Sources->Data Source Actions->create New Data Source
3.3 JDBC Driver Class 不能随便添 Data Source URL可能是jdbc:mysql://IP:port
JNDI Name:MyDataSource
Data Source URL:jdbc:mysql://127.0.0.1:3306/datasource
JDBC Driver Class:org.gjt.mm.mysql.Driver
User Name:root
Password:123456
其余默认
Validation Query:可以不填
3.4 Save->Commit Change
4.在%TOMCAT_HOME%\conf\catalina\localhost\testapp.xml加入
添加<ResourceLink global="MyDataSource" name="MyDataSource" type="javax.sql.DataSource"/>
如果发布是%TOMCAT_HOME%\conf\server.xml配置则在<context> ... </context> 里面加入
----------------------------按照如上步骤不会出现以下错误
Cannot create JDBC driver of class '' for connect URL 'null'
Name MyDataSource is not bound in this Context
Cannot load JDBC driver class 'org.git.mm.mysql.Driver'
---------------------------------------------------
测试代码Test.jsp
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@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;
Connection conn=null;
Statement stmt=null;
try{
InitialContext ctx=new InitialContext();
ds=(DataSource)ctx.lookup("java:comp/env/MyDataSource");
conn = ds.getConnection();
stmt = conn.createStatement();
String strSql="select * from user";
ResultSet rs=stmt.executeQuery(strSql);
while(rs.next()){
out.println("用户名为 : " + rs.getString(1));
}
if(rs!=null) {rs.close();};
if(stmt!=null) {stmt.close();};
if(conn!=null) {conn.close();};
}
catch (SQLException e) {
// display SQL specific exception information
System.out.println("*************************" );
System.out.println("SQLException in main: " + e.getMessage() );
System.out.println("** SQLState: " + e.getSQLState());
System.out.println("** SQL Error Code: " + e.getErrorCode());
System.out.println("*************************" );
e.printStackTrace();
}
catch (Exception e) {
System.out.println("Exception in main: " + e.getMessage() );
e.printStackTrace();
}
%>
</head>
<body>
</body>
</html>