H__D  

数据源的由来

  在Java开发中,使用JDBC操作数据库的四个步骤如下:

      ①加载数据库驱动程序(Class.forName("数据库驱动类");)
      ②连接数据库(Connection con  = DriverManager.getConnection();)
      ③操作数据库(PreparedStatement stat = con.prepareStatement(sql);stat.executeQuery();)
      ④关闭数据库,释放连接(con.close();)
  也就是说,所有的用户都需要经过此四步进行操作,但是这四步之中有三步(①加载数据库驱动程序、②连接数据库、④关闭数据库,释放连接)对所有人都是一样的,而所有人只有在操作数据库上是不一样,那么这就造成了性能的损耗。
  那么最好的做法是,准备出一个空间,此空间里专门保存着全部的数据库连接,以后用户用数据库操作的时候不用再重新加载驱动、连接数据库之类的,而直接从此空间中取走连接,关闭的时候直接把连接放回到此空间之中。
  那么此空间就可以称为连接池(保存所有的数据库连接),但是如果要想实现此空间的话,则必须有一个问题要考虑?
      1、 如果没有任何一个用户使用连接,那么那么应该维持一定数量的连接,等待用户使用。
      2、 如果连接已经满了,则必须打开新的连接,供更多用户使用。
      3、 如果一个服务器就只能有100个连接,那么如果有第101个人过来呢?应该等待其他用户释放连接
      4、 如果一个用户等待时间太长了,则应该告诉用户,操作是失败的。
   如果直接用程序实现以上功能,则会比较麻烦,所以在Tomcat 4.1.27之后,在服务器上就直接增加了数据源的配置选项,直接在服务器上配置好数据源连接池即可。在J2EE服务器上保存着一个数据库的多个连接。每一个连接通过DataSource可以找到。DataSource被绑定在了JNDI树上(为每一个DataSource提供一个名字)客户端通过名称找到在JNDI树上绑定的DataSource,再由DataSource找到一个连接。如下图所示:
   
  那么在以后的操作中,除了数据库的连接方式不一样之外,其他的所有操作都一样,只是关闭的时候不是彻底地关闭数据库,而是把数据库的连接放回到连接池中去。
  如果要想使用数据源的配置,则必须配置虚拟目录,因为此配置是在虚拟目录之上起作用的。需要注意的是,如果要想完成以上的功能,在Tomcat服务器上一定要有各个数据库的驱动程序。

配置JDNI数据源

  1、将数据库连接的驱动jar包放入,tocmat的lib目录

  2、在tomcat服务器的conf目录下context.xml配置文件中,配置数据源

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!--
 3   Licensed to the Apache Software Foundation (ASF) under one or more
 4   contributor license agreements.  See the NOTICE file distributed with
 5   this work for additional information regarding copyright ownership.
 6   The ASF licenses this file to You under the Apache License, Version 2.0
 7   (the "License"); you may not use this file except in compliance with
 8   the License.  You may obtain a copy of the License at
 9 
10       http://www.apache.org/licenses/LICENSE-2.0
11 
12   Unless required by applicable law or agreed to in writing, software
13   distributed under the License is distributed on an "AS IS" BASIS,
14   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   See the License for the specific language governing permissions and
16   limitations under the License.
17 -->
18 <!-- The contents of this file will be loaded for each web application -->
19 <Context>
20 
21     <!-- Default set of monitored resources. If one of these changes, the    -->
22     <!-- web application will be reloaded.                                   -->
23     <WatchedResource>WEB-INF/web.xml</WatchedResource>
24     <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
25 
26     <!-- Uncomment this to disable session persistence across Tomcat restarts -->
27     <!--
28     <Manager pathname="" />
29     -->
30     <!--
31       其中name  指定数据源在容器中的JNDI名
32       driverClassName 指定连接数据库的驱动
33       url       指定数据库服务的URL
34       username  指定连接数据库的用户名
35       password  指定连接数据库的密码
36       maxActive 最大连接数据库连接数
37       maxIdle 最大等待连接中的数量
38       maxWait 最大等待毫秒数, 单位为 ms
39     -->
40     <Resource name="jdbc/datasource" 
41       auth="Container"
42       type="javax.sql.DataSource"
43       maxActive="100" 
44       maxIdle="30" 
45       maxWait="10000"
46       driverClassName="com.mysql.jdbc.Driver"
47       url="jdbc:mysql://127.0.0.1:3306/test?allowPublicKeyRetrieval=true" 
48       username="admin" 
49       password="admin"
50       characterEncoding="utf-8" />
51 </Context>

  3、在tomcat的conf/web.xml中引入数据源,或者在项目的web.xml中引入,在文件最后,引入方式如下:

1     <resource-ref>
2       <description>DB Connection</description>
3       <res-ref-name>jdbc/datasource</res-ref-name>
4       <ref-type>javax.sql.DataSource</ref-type>
5       <res-auth>Container</res-auth>
6     </resource-ref>

   4、测试,在webapps中,新建目录test-jdbc,增加文件jdbc.jsp,如下:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@page import="java.sql.*"%>
 4 <%@page import="javax.sql.DataSource"%>
 5 <%@page import="javax.naming.*"%>
 6 
 7 
 8 <!DOCTYPE html>
 9 <html>
10 <head>
11 <meta charset="UTF-8">
12 <title>Insert title here</title>
13 </head>
14 <body>
15 <h2>Tomcat JDBC</h2>
16     <%
17     // 初始化Context,使用InitialContext初始化Context
18     Context ctx=new InitialContext(); 
19     /*
20         通过JNDI查找数据源,该JNDI为java:comp/env/jdbc/dstest,分成两个部分
21         java:comp/env是Tomcat固定的,Tomcat提供的JNDI绑定都必须加该前缀
22         jdbc/datasource 是定义数据源时的数据源名
23     */
24     DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/datasource");
25     // 获取数据库连接
26     Connection conn=ds.getConnection();
27     // 获取Statement
28     Statement stmt=conn.createStatement();
29     // 执行查询,返回ResulteSet对象
30     ResultSet rs=stmt.executeQuery("select * from user");
31     int count = rs.getMetaData().getColumnCount();
32     while(rs.next()) {//遍历行,next()方法返回值为Boolean,当存在数据行返回true,反之false
33         for(int i = 1; i <= count; i++) {//遍历列
34             out.print(rs.getString(i));
35             if(i < count) {
36                 out.print("\t-\t");//为数据隔开美观,没实际意义
37             }
38         }
39         out.println();
40     }  
41     %>
42 </body>
43 </html>

 

   5、启动tomcat,并且在浏览器上访问,地址:http://localhost:8080/test-jdbc/jdbc.jsp

    

 

 

posted on 2019-08-19 19:28  H__D  阅读(2446)  评论(0编辑  收藏  举报