
1、创建数据库Student,表student
2、配置server.xml文件。Tomcat安装目录下conf中server.xml文件。
<GlobalNamingResources>
<Resource
name="jdbc/DBPool"
type="javax.sql.DataSource"
password=""
driverClassName="com.mysql.jdbc.Driver"
maxIdle="2"
maxWait="5000"
username="root"
url="jdbc:mysql://localhost:3306/student"
maxActive="3"
/>
</GlobalNamingResources>
name:指定连接池的名称
type:指定连接池的类,他负责连接池的事务处理
url:指定要连接的数据库
driverClassName:指定连接数据库使用的驱动程序
username:数据库用户名
password:数据库密码
maxWait:指定最大建立连接等待时间,如果超过此时间将接到异常
maxIdle:指定连接池中连接的最大空闲数
maxActive:指定连接池最大连接数
3、配置web.xml文件。
<web-app>
<resource-ref>
<description>mysql数据库连接池配置</description>
<res-ref-name>jdbc/DBPool</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
</web-app>
4、配置context.xml文件
与server.xml文件所在的位置相同。
<Context>
<ResourceLink
name="jdbc/DBPool"
type="javax.sql.DataSource"
global="jdbc/DBPool"
/>
</Context>
5、测试
DataSource pool = null
Context env = null
Connection conn = null
Statement st = null
ResultSet rs = null
try{
env = (Context)new InitialContext().lookup("java:comp/env")
//检索指定的对象,返回此上下文的一个新实例
pool = (DataSource)env.lookup("jdbc/DBPool")
//获得数据库连接池
if(pool==null){out.printl("找不到指定的连接池!")}
con = pool.getConnection()
st = con.createStatement()
rs = st.executeQuery("select * from student")
}catch(Exception ex){out.printl(ne.toString())}
javapublic static Connection getConnection() throws NamingException,SQLException{
//context接口提供了查找JNDI Resource的接口
Context ct=new InitialContext()
//datasource对象由tomcat提供,所以不能在程序中实例化获得,需查找获取
DataSource ds=(DataSource)ct.lookup("java:comp/env/communication")/
/获取datasource对象后,由对象的getConnection方法获取一个连接对象
return ds.getConnection() }
http://wenku.baidu.com/view/fdf8bb0eeff9aef8941e06d2.html
1.让tomcat容器启动创建数据库连接池2.在某个项目中关联数据库连接池,3.取得数据库连接池并使用。使用包括,当拿到数据库连接后,可以通过2种方式来使用,1.使用jstl的标签,2.封装成返回connection的方法。欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)