Java使用JNDI技术连接数据库

JNDI的作用:避免了程序与数据库之间的紧耦合,使应用更加易于配置、易于部署。

JNDI的使用:

1.在META-INF下配置context.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/2002/xmlspec/dtd/2.10/xmlspec.dtd">
<Context>
<Resource name="jdbc/test"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=utf-8"
username="root"
password="rot"
maxActive="100"  //连接池的最大数据库连接数。设为0表示无限制
maxIdle="30"    //最大等待连接中的数量,设为0表示没有限制
maxWait="10000   //最大等待毫秒数,单位为ms,超过时间会出错误信息

"/>
</Context>


2.在web.xml文件配置:


<resource-ref>
    <description>DBConn</description>
    <res-ref-name>jdbc/test</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>

<!– 指定管理所引用资源的Manager, 它有两个可选值:Container和Application.Container表示由容器来创建和管理Resource>
  </resource-ref>

3.添加数据驱动文件


4.在程序中引用数据源

import java.sql.Connection;


import javax.naming.InitialContext;
import javax.sql.DataSource;


public class DbConn {
//通过JNDI连接池的方式
public static Connection getConnection(){
try{
InitialContext context=new InitialContext();
DataSource dSource=(DataSource)context.lookup("java:comp/env/jdbc/test");
Connection conn=dSource.getConnection();
return conn;
}catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
return null;
}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值