1.java web tomcat 数据源

1.JDBC的操作原理:

1)加载数据库驱动程序,数据库驱动程序通过classpath配置

2)同过DriverManager类取得数据库连接对象

3)通过Connection 实例化PreparedStatement对象,编写SQL命令操作数据库

4)数据库是资源操作,操作完毕后一定记得关闭连接释放资源

2.在tomcat中使用数据库连接池

在web容器中,数据库的连接池都是通过数据源(javax.sql.Datasource)来访问的,即通过javax.sql.DataSoruce 来取得一个Connection对象,要想得到DataSource 对象则需要用JNDI来进行查找。

1)配置server.xml

<Context reloadable="true">

    <!-- Default set of monitored resources -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
	
    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->

    <!-- Uncomment this to enable Comet connection tacking (provides events
         on session expiration as well as webapp lifecycle) -->
    <!--
    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
    -->
	
	<Resource name="jdbc/mysqlds" <!--配置连接池名称,为jdbc/mysqlds-->
	auth="Container" 
	type="javax.sql.DataSource" 
        maxActive="100" <!--最大连接数-->
	maxIdle="30" <!--最小连接数-->
	maxWait="10000" <!--用户等待的最大时间-->
	username="root" <!--数据库用户名-->
	password="" <!--数据库密码-->
	driverClassName="com.mysql.jdbc.Driver" <!--数据库驱动程序-->     
	url="jdbc:mysql://localhost:3306/myblog"/> 
</Context>
2)测试连接

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@page import ="javax.naming.*" %>
<%@page import ="javax.sql.*" %>
<%@page import ="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body><br>
	<% 
		String DSNAME = "java:comp/env/jdbc/mysqlds"; 
		Context context = new InitialContext(); 
		DataSource ds = (DataSource)context.lookup(DSNAME);
		Connection conn = ds.getConnection();
	 %>
	 <%=conn %>
</body>
</html>

输出: jdbc:mysql://localhost:3306/myblog, UserName=root@localhost, MySQL-AB JDBC Driver     测试成功


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值