西西软件园多重安全检测下载网站、值得信赖的软件下载站!
软件
软件
文章
搜索

首页编程开发java → 在NetBeans中设置数据库连接池教程

在NetBeans中设置数据库连接池教程

相关软件相关文章发表评论 来源:西西整理时间:2011/6/14 14:40:24字体大小:A-A+

作者:西西点击:454次评论:0次标签: NetBeans

Java SE&NetBeans IDEV8.1 复合软件包
  • 类型:编程工具大小:93.9M语言:中文 评分:8.0
  • 标签:
立即下载

  以往要设置数据库连接池,需要借助于第三方软件。但现在NetBeans所带的Tomcat 5.5.7及Sun Application Server 8均可以直接设置。下面谈谈如何在Tomcat 5.5.7下设置。
  1. 下载数据库的专用连接驱动,并将其复制到C:Program Filesetbeans-4.1entERPrise1jakarta-tomcat-5.5.7commonlib文件夹下面。
  假设所用数据库是Sybase的Adaptive Server Anywhere,从Sybase官方站点下载JConnect-6_0,从中抽取出jconn3这个驱动,复制到上述文件夹下。
  2. 启动Tomcat,在IE输入http://localhost:8084/admin/,以管理员身份登录管理。用户登录的方法可参考第5楼。点击Resources下的Data Sources,在右边Data Source Actions的下拉框中选Create New Data Source,按下表示范填写:
JNDI Name: sybase/poolDB  /* 根据喜好填 */
Data Source URL: JDBC:sybase:Tds:<localhost>:<端口号>
/* 数据库的地址,此为jconn3的形式,端口号需查询确认,但一般都是固定的,除非自己更改 */
JDBC Driver Class: com.sybase.jdbc3.jdbc.SybDriver  /* jconn3的驱动 */
User Name: dba            /* 用户名,默认为dba */
Password: ***             /* 密码,默认为sql */
Max. Active Connections: 4      /* 最大活动连接数 */
Max. Ide Connections: 2        /* 最大空闲连接数 */
Max. Wait for Connecton: 5000     /* 等待连接的最大秒数 */
Validation Query:           /* 验证字符串,可不填 */

  按"Save",再按"Commit Changes",Tomcat在后台将此变化保存到server.XML文件中。"Commit Changes"是最容易忘记的,小心。
  3. 以下均转入NetBeans环境中设置。在context.xml修改的内容:
<Context path="/Matrix">
 <ResourceLink global="sybase/poolDB" name="sybase/poolDB" type="Javax.sql.DataSource"/>
</Context>
  "/Matrix"为此Web应用的根地址,表现为http://localhost:8084/Matrix。
  4. 在web.xml中加入:
<resource-ref>
<description>Sybase Database Connection Pool</description>
<res-ref-name>sybase/poolDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
  5. 好了,可以使用连接池了。以下代码为在JSP文件中使用JSTL标签库的范例。
<sql:query var="queryresults" dataSource="sybase/poolDB">
SELECT * FROM customer
</sql:query>


以前习惯了用jbuilder和eclipse,也习惯了它们的那种方便的配置资源的方式。前不久看到网上的一片文章说的是NetBeans的新的功能和它的许多优于其它java集成开发环境的特性,强烈的好奇心驱使我下载并安装了NetBeans。新建了一个web项目测试了一下,真的有许多过人之处。特别是它和页面开发工具Dreamweaver配合,用DW开发页面,NB开发java程序,把两者指向一个共同的目录,修改过页面后只需要刷新就可以在浏览器中直接看到效果了,几乎不用配置什么东西。于是我现在的所有的项目都使用NB。至于其它的优点就不多说了,建议你下载并感受一下那种方便、快捷吧。

由于NB默认的是使用内置的tomcat作为web服务器,手头的一个项目对数据库的操作比较频繁,考虑用数据库连接池技术以减少程序的响应时间。以前都是直接在tomcat的管理员页面中配置数据库连接池,方便而且不容易出错。准备用同样的方法在NB中配置一下,但配置的过程中发现有一些不同之处,现在终于配置成功,写出来供大家参考。下面开始:

启动NetBeans5.5,新建一个web项目,名称任意,新建成功后会有一个自动的index.jsp页面。然后编译并运行项目,这时候会在IDE的下方有一些相关的信息,这些信息也是我们发现错误的有效途径。运行后会自动打开IE,并运行类似如下路径的jsp文件:http://localhost:8084/Try/,现在把路径端口后面的项目名删除,进入Tomcat的默认页面http://localhost:8084/,点击该页面左边的Tomcat Administration链接进入管理员的登录页面。由于Tomcat的安装是包含在NB中的,我们并没有对Tomcat的账户进行配置,所以登录请要先配置Tomcat的tomcat-users.xml文件,它所在文件夹的相对路径是:netbeans-5.5\enterprise3\apache-tomcat-5.5.17\conf。把该文件修改如下:

<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>

<role rolename="tomcat"/>

<role rolename="admin"/>//新建

<role rolename="role1"/>

<user username="both" password="tomcat" roles="tomcat,role1"/>

<user username="tomcat" password="tomcat" roles="tomcat"/>

<user username="admin" password="123123" roles="admin"/>//新建

<user username="role1" password="tomcat" roles="role1"/>

</tomcat-users>


修改后就可以用admin的用户名,123123的密码登录了。登陆后展开Resources目录,选择Data Sources,单击右边Data Sourec Actions下拉菜单,选择Create New Date Sourec.分别填写其中的属性的值。JNDI Name是连接池的名字,在java程序中要用到;Data Source URL是数据库连接字串,格式为jdbc:mysql://localhost/(数据库名);JDBC Driver Class是你要使用的JDBC连接类。User Name、Password是数据库的用户名和密码;下面的三个分别是数据库最大连接数、数据库最大空闲连接数、数据库最大等待连接限制。最后一个是验证连接用的查询语句,可以不填。设定好后保存,并单击上面的Commit Changes提交。

修改C:\Documents and Settings\你的用户名
\.netbeans\5.5\apache-tomcat-5.5.17_base\conf\Catalina\localhost文件夹下的和你的项目同名的xml文件,修改后如下:

<?xml version="1.0" encoding="UTF-8"?>
<Context
docBase="D:/my_nb/Try/build/web">
<ResourceLink global="jdbc/myehow" name="jdbc/myehow" type=
"javax.sql.DataSource"/>//定义要使用的连接池
</Context>

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@page import="java.sql.*" %>
<%@page import="javax.sql.*" %>
<%@page import="javax.naming.*" %>
<%

Connection con=null;

Statement stm=null;

ResultSet rs=null;

try{

InitialContext ctx=new InitialContext();

DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/myehow");

con=ds.getConnection();

stm=con.createStatement();

rs=stm.executeQuery("select * from ehow");

while(rs.next()){

String name=rs.getString(2);

out.println(name);

out.print("<br>");

}



现在就可以在项目中使用这个连接池了,下面给出一个仅供参考的数据库连接池的测试文件,如果要在项目中用的话应该写在一个bean中,数据库的内容在下面给出。测试文件如下:



}catch(Exception e){

out.print(e.getMessage());

e.printStackTrace();

}finally{

if(rs!=null){

try{

rs.close();

}catch(SQLException e){

}

}

if(stm!=null){

try{

stm.close();

}catch(SQLException e){

}

}


if(con!=null){

try{

con.close();

}catch(SQLException e){

}

}

}



%>


数据库中只有一个表,表中有两个字段,其中id是主键,int型。Name,字符型长度30。

好了,现在运行项目,就可以看到数据库中的信息了。

项目的部署:项目开发完成当然要部署到服务器上,由于NB已经为我们完成了大量的工作,只需要把数据库备份,把NB的dist文件夹下的项目名.war文件拷贝到服务器上,在服务器的Tomcat的server.xml文件任意指定一个虚拟目录就可以了(不要忘了先配置连接池!),数据库还原后,就一切OK了。


在NB运行时使用的tomcat-users.xml并不是程序目录下的那个文件,而是在C盘下的某个目录下,具体名字不记得了,自己搜索就是了


把mysql驱动包分别放到%TOMCAT_HOME%/lib 和你的应用的WEB-INF\lib文件夹下面

1、修改%TOMCAT_HOME%/conf/server.xml,添加如下内容(部分参数请本地化):

<Context path="/web" docBase="web" debug="0" reloadable="true" crossContext="true">
<Resource name="jdbc/query" auth="Container" type="javax.sql.DataSource" driverClassName="org.gjt.mm.mysql.Driver"

maxIdle="20" maxWait="5000" username="username" password="password" url="jdbc:mysql://localhost:3306/DataBaseName"

maxActive="100" removeAbandoned="true" removeAbandonedTimeout="60" logAbandoned="true"/>
</Context>

2、修改对应应用的web.xml,在</web-app>前添加如下内容:

<ResourceLink name="jdbc/query" global="jdbc/query" type="javax.sql.DataSourcer"/>

重启tomcat,大功搞成!

应用实例如下:

<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="javax.naming.Context" %>
<%@ page import="javax.sql.DataSource"%>
<%@ page import="javax.naming.InitialContext"%>
<%@ page import="java.sql.*"%>
<html>
<body>
123
<%
DataSource ds = null;
try{
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
//从Context中lookup数据源。
ds = (DataSource)envCtx.lookup("jdbc/query");
if(ds!=null)
{
out.println("已经获得DataSource!");
out.println("<br>");
Connection conn = ds.getConnection();
Statement stmt=conn.createStatement();
ResultSet rst=stmt.executeQuery("select * from cs_order");//从一个已存在的表中读取数据
out.println("以下是从数据库中读取出来的数据:<br>");
while(rst.next()){
out.println("<br>");
out.println(rst.getString(8));}

}
}
catch(Exception ne)
{
out.println("出现如下错误:<br>");
out.println(ne);
}

%>
</body>
</html>

-------------------------------------------------------------------------------------------

参考:

1.MySQL数据库版本:mysql-5.0.27

2.TomCat版本:6.0

3.数据库驱动程序:mysql-connector-java-XXX

4.Server.xml文件内容:

<!-- Note: A "Server" is not itself a "Container", so you may not
define subcomponents such as "Valves" at this level.
Documentation at /docs/config/server.html
-->
<Server port="8005" shutdown="SHUTDOWN">

<!--APR library loader. Documentation at /docs/apr.html -->
<Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
<!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
<Listener className="org.apache.catalina.core.JasperListener" />
<!-- JMX Support for the Tomcat server. Documentation at /docs/non-existent.html -->
<Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />

<!-- Global JNDI resources
Documentation at /docs/jndi-resources-howto.html
-->



<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users
-->
<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml" />
</GlobalNamingResources>

<!-- A "Service" is a collection of one or more "Connectors" that share
a single "Container" Note: A "Service" is not itself a "Container",
so you may not define subcomponents such as "Valves" at this level.
Documentation at /docs/config/service.html
-->
<Service name="Catalina">

<!-- A "Connector" represents an endpoint by which requests are received
and responses are returned. Documentation at :
Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
Java AJP Connector: /docs/config/ajp.html
APR (HTTP/AJP) Connector: /docs/apr.html
Define a non-SSL HTTP/1.1 Connector on port 8080
-->
<Connector port="8080" protocol="HTTP/1.1"
maxThreads="150" connectionTimeout="20000"
redirectPort="8443" />

<!-- Define a SSL HTTP/1.1 Connector on port 8443
This connector uses the JSSE configuration, when using APR, the
connector should be using the OpenSSL style configuration
described in the APR documentation -->
<!--
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" />
-->

<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />


<!-- An Engine represents the entry point (within Catalina) that processes
every request. The Engine implementation for Tomcat stand alone
analyzes the HTTP headers included with the request, and passes them
on to the appropriate Host (virtual host).
Documentation at /docs/config/engine.html -->

<!-- You should set jvmRoute to support load-balancing via AJP ie :
<Engine name="Standalone" defaultHost="localhost" jvmRoute="jvm1">
-->
<Engine name="Catalina" defaultHost="localhost">

<!--For clustering, please take a look at documentation at:
/docs/cluster-howto.html (simple how to)
/docs/config/cluster.html (reference documentation) -->
<!--
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
-->

<!-- The request dumper valve dumps useful debugging information about
the request and response data received and sent by Tomcat.
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.valves.RequestDumperValve"/>
-->

<!-- This Realm uses the UserDatabase configured in the global JNDI
resources under the key "UserDatabase". Any edits
that are performed against this UserDatabase are immediately
available for use by the Realm. -->
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
resourceName="UserDatabase"/>


<!-- Define the default virtual host
Note: XML Schema validation will not work with Xerces 2.2.
-->
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true"
xmlValidation="false" xmlNamespaceAware="false">

<!-- SingleSignOn valve, share authentication between web applications
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.authenticator.SingleSignOn" />
-->

<!-- Access log processes all example.
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.valves.FastCommonAccessLogValve" directory="logs"
prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/>
-->
<!-- JNDI Setting -->

<Context path="/MingPian" docBase="MingPian"
debug="5" reloadable="true" crossContext="true">

<!-- maxActive: Maximum number of dB connections in pool. Make sure you
configure your mysqld max_connections large enough to handle
all of your db connections. Set to 0 for no limit.
-->

<!-- maxIdle: Maximum number of idle dB connections to retain in pool.
Set to -1 for no limit. See also the DBCP documentation on this
and the minEvictableIdleTimeMillis configuration parameter.
-->

<!-- maxWait: Maximum time to wait for a dB connection to become available
in ms, in this example 10 seconds. An Exception is thrown if
this timeout is exceeded. Set to -1 to wait indefinitely.
-->

<!-- username and password: MySQL dB username and password for dB connections -->

<!-- driverClassName: Class name for the old mm.mysql JDBC driver is
org.gjt.mm.mysql.Driver - we recommend using Connector/J though.
Class name for the official MySQL Connector/J driver is com.mysql.jdbc.Driver.
-->

<!-- url: The JDBC connection url for connecting to your MySQL dB.
The autoReconnect=true argument to the url makes sure that the
mm.mysql JDBC Driver will automatically reconnect if mysqld closed the
connection. mysqld by default closes idle connections after 8 hours.
-->

<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="123456" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/dbname?autoReconnect=true"/>

</Context>
</Host>
</Engine>
</Service>
</Server>

5:程序目录下web.xml文件内容:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
<description>MySQL Test App</description>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>

6:程序目录为:MingPian,这个文件夹的名字是和Server.xml中的<Context path="/MingPian" docBase="MingPian"
debug="5" reloadable="true" crossContext="true">目录对应的,否则连接不上.

如果程序的目录为空,则这里的<Context path "/" docBase-"" debug="5" reloadable="true" crossContext="true">

我的电脑上Context.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<Context crossContext="true" debug="0" docBase="web" path="/DataWeb" reloadable="true">
<Resource auth="Container" driverClassName="org.gjt.mm.mysql.Driver" logAbandoned="true" maxActive="2" maxIdle="4" maxWait="5000" name="mysql/poolDB" password="123456" removeAbandoned="true" removeAbandonedTimeout="60" type="javax.sql.DataSource" url="jdbc:mysql://localhost:3306/sample" username="root"/>
</Context>


Web.xml文件
<resource-ref>
<description>jdbc:mysql://localhost:3306/sample [root on Default schema]</description>
<res-ref-name>mysql/poolDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>

NetBeans IDE V6.9 官方简体中文版:http://www.cr173.com/soft/10288.html

    eclipse
    (119)eclipse
    是对的扩展,利用它我们可以在数据库和的开发发布以及应用程序服务器的整合方面极大的提高工作效率。它是功能丰富的集成开发环境,包括了完备的编码调试测试和发布功能,完整支持,,,,,,,。分类在结构上,的特征可以被分为类模型开发工具开发工具应用程序服务器的连接器项目部署服务数据库服务整合帮助...更多>>
    html编辑器
    (73)html编辑器
    我们做网页的时候最难找的就是编辑器,网上找一个吧,要不是图片上传错误,就是到处都是错误,垃圾太多.大家都需要一个简单,速度快的.西西为您提供最好用的编辑器一站式下载编辑器定义编辑器指的是一类编辑制作工具,可自定义窗囗,编辑主题索引,可选择添搜索页,无任何不自由。编辑器哪个好用小编个人比较喜欢使用和,这两款编辑器软件都有不错的表现。至于编辑器哪个好用,这就要根据你的个人需求去选择对应的编辑器啦...更多>>
    jre下载
    (45)jre下载
    是程序的运行环境,如果你想想编写程序那就要装,是整个的核心,包括了运行环境工具和基础类库。语言由于它的跨平台性,经常是编程语言排行榜的榜首,年月份编程语言排行榜,本月变化较大的是与位置互换,领衔称霸,份额略有上升。前三甲为。当然,如果你只是想在上运行程序,那么装上环境就了。,,文件怎么运行如果是完整的可执行文件,那么是可以双击运行的,前提,你的机器上一定有合适的版本装过后文件会被关联到用.打开,,直接...更多>>
    • Java Runtime Environment(JRE7)V7

      05-15 / 26.0M

      推荐理由:java 运行库 runtime environment 7,安装了它就可以运行java的程序了。Java语言恐怕是稳居网路应用程序语言
    • jdk7 64位7u80 官方正式版(Java SE

      08-19 / 139.3M

      推荐理由:JDK是一个开发环境,用于构建应用程序,applet程序,和使用Java编程语言的组成部分。Java Development Kit(
    • Java SE Runtime Environment 88.0

      02-13 / 58.9M

      推荐理由:Java语言恐怕是稳居网路应用程序语言的首选了,这都要归功于它高度的安全性以及跨平台的特性,几乎在目前所有
    • JDK 6(Java SE Development Kit)6u

      03-10 / 57.9M

      推荐理由:适用于您的计算机(windows)的 Java 软件,即 Java Runtime Environment,也称为 Java Runtime、运行时环境、
    • Java SE Development Kit (JDK7)7u

      08-19 / 137.5M

      推荐理由:JDK 7u51 发布,该版本修复了浏览器插件的严重的安全漏洞:CVE-2013-1493,Oracle 强烈建议使用 Java 浏览器
    • JRE(Java Runtime Environment)v6.

      05-15 / 13.8M

      推荐理由:JAVA运行必不可少的运行环境,你只要运行JAVA,必须安装JRE,目前还没有别的运行平台可以代替了,它包括Jav
    eclipse中文版下载
    (27)eclipse中文版下载
    是一个开放源代码的基于的可扩展开发平台。还包括插件开发环境,,这个组件主要针对希望扩展的软件开发人员,因为它允许他们构建与环境无缝集成的工具。它只是一个框架和一组服务,用于通过插件组件构建开发环境。幸运的是,附带了一个标准的插件集,包括开发工具,。汉化方法把语言包中的,文件夹直接覆盖到安装目录中,或者把汉化包放到目录下面。常用快捷键.快速修复.删除当前行.复制当前行到下一行.或者说是空格由于后者与输入法...更多>>
    Visual Studio
    (42)Visual Studio
    是什么学是学什么首先是一个软件集成开发环境编译编辑调试和。软件开发工具的灵魂微软基础类库模板类库其他的,如,,,..,简称或者.,是微软推出的一款编译器,将高级语言翻译为机器语言低级语言的程序。是一个功能强大的可视化软件开发工具。自年公司推出.后,随着其新版本的不断问世,已成为专业程序员进行软件开发的首选工具。虽然微软公司推出了..,但它的应用的很大的局限性,只适用于和.。所以实际中,更多的是以.为平台。.不...更多>>

    相关评论

    阅读本文后您有什么感想? 已有人给出评价!

    • 8 喜欢喜欢
    • 3 顶
    • 1 难过难过
    • 5 囧
    • 3 围观围观
    • 2 无聊无聊

    热门评论

    最新评论

    发表评论 查看所有评论(0)

    昵称:
    表情: 高兴 可 汗 我不要 害羞 好 下下下 送花 屎 亲亲
    字数: 0/500 (您的评论需要经过审核才能显示)