tomcat 7 jndi mysql,tomcat7添加mysql数据库的jndi数据源

1.将数据库驱动复制到%TOMACT%/lib目录下,以便配置文件和程序代码使用

对于MySQL数据库,jar包下载地址:http://dev.mysql.com/downloads/connector/j/

2.在MySQL中建好数据库,这里建一个名为empdb的数据库(后面配置文件中需要用到这个名字)

3.写配置文件WEB-INF/web.xml

xmlns="http://java.sun.com/xml/ns/javaee"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

id="WebApp_ID" version="3.0">

jndiDemo2

index.html

index.htm

index.jsp

default.html

default.htm

default.jsp

DB

jdbc/EmployeeDB

javax.sql.DataSource

Container

4.写配置文件META-INF/context.xml,注意数据库名要一致

driverClassName="com.mysql.jdbc.Driver"

username="root"

password=""

type="javax.sql.DataSource"

url="jdbc:mysql://localhost:3306/empdb?characterEncoding=UTF-8"/>

5.写测试代码index.jsp

pageEncoding="UTF-8"%>

Insert title here

String user = "root";

String password = "";

String driverName = "com.mysql.jdbc.Driver";

String connectURL = "jdbc:mysql://localhost:3306/empdb?useUnicode=true&characterEncoding=UTF-8";

Connection conn = null;

try {

Class.forName(driverName);

conn = DriverManager.getConnection(connectURL, user, password);

out.print("传统JDBC方式连接成功");

} catch (Exception e) {

out.print("传统JDBC方式连接失败");

}

/*

Statement stmt = null;

ResultSet rs = null;

stmt = conn.createStatement();

String sql = "select * from foodorderinfo";

rs = stmt.executeQuery(sql);

StringBuffer strbf = new StringBuffer();

while (rs.next()) {

String buywhat = rs.getString("buywhat");

strbf.append(buywhat);

}

rs.close();

stmt.close();*/

%>

Context initCtx;

initCtx = new InitialContext();

Context envCtx = (Context) initCtx.lookup("java:comp/env");

DataSource ds = (DataSource) envCtx.lookup("jdbc/EmployeeDB");

Connection con = ds.getConnection();

if (con != null) {

out.print("JNDI方式连接成功");

} else {

out.print("JNDI方式连接失败");

}

%>

部署运行,大功告成!

与用定制的javabean配置数据源相比,这里要求开发者需要基础的数据库知识。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值