Jsp_Servlet_JavaBean_Chapter5,6理论笔记

1、数据库连接池的使用。
* 基本原理

* 使用的步骤
1 配置:<TOMCAT_HOME>/conf/context.xml
<Resource name="jdbc/test"
type="javax.sql.DataSource"
auth="Container"
maxActive="80"
maxIdle="30"
maxWait="10000"
username="root"
password="123456"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/studentdb" />

说明:除了上面的配置方式外,还可以到web项目的META-INFO目录下建立context.xml文件,在此文件
中配置数据源
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/test"
type="javax.sql.DataSource"
auth="Container"
maxActive="80"
maxIdle="30"
maxWait="10000"
username="root"
password="123456"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/studentdb" />
</Context>

2 将连接数据库的驱动程序放到以下目录中
<TOMCAT_HOME>/common/lib(Tomcat5)
<TOMCAT_HOME>/lib(Tomcat6)

3 在应用程序的web.xml中进行配置
<resource-ref>
<res-ref-name>jdbc/test</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

说明:上面的配置可有可无,意思是告诉其他人,当前应用程序依赖于容器的实现,也就是说它用了Tomcat的数据库连接池的实现
以后如果将该项目发布到其他web服务器(WebLogic)的时候,要在其他web服务器上配置数据库连接池。这段配置就是一个
提示的作用。

4 在Java类中根据JNDI获得数据源(DataSoure),通过数据源取得连接对象

/**
* 从数据源中取连接
* @return
*/
public static Connection getCon() {
Connection con = null;

try {
Context context = new InitialContext(); //得到上下文对象,这个对象中包含了一些容器的环境信息
DataSource source = (DataSource) context.lookup("java:comp/env/jdbc/test"); //根据JNDI查找数据源
con = source.getConnection(); //从数据源内部的连接池中取出一个连接
} catch (Exception ex) {
ex.printStackTrace();
}

return con;
}


2、使用JNDI获取数据源

3、读取基于属性文件的数据连接信息
dbconfig.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/studentdb
username=root
password=123456

Env.java

public class Env extends Properties {

private static Env instance = null;

private Env() {
InputStream is = this.getClass().getClassLoader().getResourceAsStream("dbconfig.properties");
try {
load(is);
} catch (Exception ex) {
ex.printStackTrace();
}
}

public static Env getInstance() {
if(instance != null) {
return instance;
} else {
makeInstance();
return instance;
}
}

private static synchronized void makeInstance() {
if(instance == null) {
instance = new Env();
}
}
}


4、通用DAO
result = ResultSupport.toResult(rs);
对rs进行封装,把ResultSet中的每一行数据封装成一个Map对象(key--列名 value--列值),整个
result就相当于是Map的一个数组

把ResultSet --> Result
ResultSet
sid name pwd age
s001 zs aaa 20
s002 ls bbb 30

Result:相当与map的数组
map{
sid=001
name=zs
pwd=aaa
age=20
}
map{
sid=002
name=ls
pwd=bbb
age=30
}

为什么要返回Result,而不返回ResultSet,是因为如果返回的是ResultSet,那么数据库连接一直要打开,
而返回Result的时候,Result的数据保存在内中的,此时可以关闭数据库连接。

步骤:
* 导入标准标签库

* 创建通用DAO:参见SQLCommandBean.java

* 创建自己的数据访问类访问通用DAO:参见StudentDao2.java
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值