TOMCAT數據源配置
網上這類文章特別多,此教程是本人實踐確保一個正常運行的一個.
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" "<%@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>
?
posted on 2006-11-08 20:18 JeromeWen 閱讀(494) 評論(0) 編輯 收藏 引用 所屬分類: JAVA