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 测试成功