数据源操作原理:
1、加载数据库驱动程序,数据库驱动程序通过classpath配置。
2、通过DriverManager类取得数据库连接对象。
3、通过Connection实例化PreparedStatement对象,编写SQL命令操作数据库。
4、数据库属于资源操作,操作完成后要关闭数据库以释放资源。
在Tomcat中使用数据库连接池:
注意:一定要配置数据库驱动程序
此时数据源连接池实在Tomcat上进行配置的,所以一定要将数据库的驱动程序复制到%TOMCAT_HOME%\common\lib文件夹中
在server.xml文件中配置数据库连接池
<Context path="/mldn" docBase="D:\mldnwebdemo" reloadable="true">
<Manager className="org.apache.catalina.session.PersistentManager">
debug=0 saveOnRestart="true"
maxActiveSession="-1" minIdleSwap="-1"
maxIdleSwap="-1" maxIdleBackup="-1"
<Store className="org.apache.catalina.session.FileStore" directory="d:\temp"/>
</Manager>
<Resource name="jdbc/mldn"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="root"
password="mysqladmin"
driverClassName="org.gjt.mm.mysql.Driver"
url="jdbc:mysql://localhost:3306/mldn"/>
</Context>
配置web.xml
<resource-ref>
<res-ref-name>jdbc/mldn</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
通过数据源取得数据库连接(测试):
<%@ page contentType="text/html" pageEncoding="GBK"%>
<%@ page import="javax.naming.*"%>
<%@ page import="javax.sql.*"%>
<%@ page import="java.sql.*"%>
<html>
<head><title></title></head>
<body>
<%
String DSNAME = "java:comp/env/jdbc/mldn" ; // 名称
Context ctx = new InitialContext() ;
DataSource ds = (DataSource) ctx.lookup(DSNAME) ;
Connection conn = ds.getConnection() ; // 从连接池中取连接
%>
<%=conn%>
<%
conn.close() ; // 表示将连接放回到池之中
%>
</body>
</html>
在本程序中可以发现,虽然真正在server.xml中配置的DataSource名称是“jdbc/mldn”,但是真正使用时却在前面加上了一个“java:comp/env/”的前缀,这实际上是JavaEE规定的一个环境命名上下文(Environment Naming Context(ENC)),主要是为了解决JNDI查找是的冲突问题。
修改DAO中的DatabaseConnection.java
<%@ page contentType="text/html" pageEncoding="GBK"%>
<%@ page import="javax.naming.*"%>
<%@ page import="javax.sql.*"%>
<%@ page import="java.sql.*"%>
<html>
<head><title></title></head>
<body>
<%
String DSNAME = "java:comp/env/jdbc/mldn" ; // 名称
Context ctx = new InitialContext() ;
DataSource ds = (DataSource) ctx.lookup(DSNAME) ;
Connection conn = ds.getConnection() ; // 从连接池中取连接
%>
<%=conn%>
<%
conn.close() ; // 表示将连接放回到池之中
%>
</body>
</html>
在Java开发中,都会使用数据库连接池进行数据库的连接操作,这样可以提升操作的性能。