Mysql database connection pool configuration tutorial

Source: Internet
Author: User

Step 1: Write javabean
Copy codeThe Code is as follows:
Package withouttears. jdbc. db;
Import java. util. HashMap;
Import java. SQL .*;
// JNDI has two core interfaces: Context and DirContext,
// Context contains basic name operations, while DirContext extends these operations to directory services.
Import javax. naming. Context;
Import javax. naming. InitialContext;
// The database resource connection Factory is a javax. SQL. DataSource object,
// It can create a java. SQL. Connection database Connection object.
Import javax. SQL. DataSource;
// Currently you can connect from Java developers (http://java.sun.com/products/jdbc/download.html#rowsetcobundle1_0)
// Download the implementation of CachedRowSet. Download and decompress the installation file, and put the "rowset. jar" file under your class directory.
// CachedRowSet is in the sun. jdbc. rowset package.
Import sun. jdbc. rowset. CachedRowSet;
/**
* Author: wiThouTTears
* Time: 2006-12-13
**/
Public class Database {
/*************************************** ***********************/
/* Function: localhost
* Function: Creates a connection pool.
**/
Private static DataSource localhost (){
DataSource ds = null;
// Get value through get () in HashMap and insert value through put,
// ContainsKey () is used to check whether the object already exists.
HashMap <Object, Object> cachedDs = new HashMap <Object, Object> ();
If (cachedDs. containsKey ("ds") // retrieve the idle database connection
{
/* Multiple database connections are established in DataSource in advance,
* These database connections are stored in the connection Pool.
* When a Java program accesses the database, it only needs to retrieve the idle database connection from the connection pool;
* When the database access process ends, the database connection is put back into the connection pool.
**/
Ds = (DataSource) cachedDs. get ("ds ");
}
Else
Try
{
/* The Context interface is provided in the javax. naming package,
* This interface allows you to bind an object to a name and retrieve an object by name.
**/
Context initCtx = new InitialContext ();
// Lookup (String name): returns the object bound to the specified name to obtain the database connection factory.
Ds = (DataSource) initCtx. lookup ("java: comp/env/jdbc/testdb ");
CachedDs. put ("ds", ds );
}
Catch (Exception e)
{
E. printStackTrace ();
}
Return ds;
}
/*************************************** ***********************/
/* Function: getConnection
* Function: Database Connection
**/
Private static Connection getConnection (){
Connection conn = null;
Try
{
DataSource ds = localhost ();
Conn = ds. getConnection ();
}
Catch (Exception e)
{
E. printStackTrace ();
}
Return conn;
}
/*************************************** ***********************/
/* Function: close
* Function: Close the connection.
**/
Private static void close (Connection conn)
{
Try
{
If (conn! = Null)
Conn. close ();
}
Catch (SQLException e)
{
E. printStackTrace ();
}
}
/*************************************** ***********************/
/* Function: executeQuery
* Function: Data Query
**/
Public static CachedRowSet executeQuery (String SQL)
{
Connection conn = null;
CachedRowSet rs = null;
Try {
Rs = new CachedRowSet ();
Conn = getConnection ();
Statement stmt = conn. createStatement ();
ResultSet rs11_stmt.exe cuteQuery (SQL );
Rs. populate (rs1 );
}
Catch (Exception e)
{
// System. out. println (e. toString ());
}
Finally {
Try
{
Conn. close ();
}
Catch (Exception ex)
{}
} Return rs;
}
/*************************************** ***********************/
/* Function: executeUpdate
* Function: update data (ADD, change, or delete data)
**/
Public static boolean executeUpdate (String SQL)
{
Boolean bl;
Bl = false;
Connection conn = getConnection ();
Try
{
Statement stmt = conn. createStatement ();
If(stmt.exe cuteUpdate (SQL)> 0)
Stmt. close ();
Bl = true;
}
Catch (SQLException e)
{
}
Finally
{
Close (conn );
}
Return bl;
}
/*************************************** ***********************/
}

Compile withouttears/db/Database. class and put it under E:/MyWorkSpace/test/WEB-INF/classes, that is, E:/MyWorkSpace/test/WEB-INF/classes/withouttears/db/Database. class. Do not make a mistake.
Step 2: Configure Tomcat (I use Tomcat 5.5.7)
1. create a test under C:/Program Files/Tomcat 5.5.7/conf/Catalina/localhost. xml, the content is as follows: <Context docBase = "E:/MyWorkSpace/test" path = "/test"> </Context>
Note: docBase is the location of your web file. I use E:/MyWorkSpace/test. Path can be written or not, but it must be written in Linux. If it is not written in Windows, I can use it for testing. It is best to write it. Test. the folder specified by xml is not in C:/Program Files/Tomcat 5.5.7/webapps/test as we usually use, but the same purpose is to use http: // localhost: 8080/test/, which is equivalent to a virtual directory under IIS and can be arbitrary.
2. Create context. xml under C:/Program Files/Tomcat 5.5.7/conf/and create a new WEB-INF/web. xml under E:/MyWorkSpace/test.
Context. xml
Copy codeThe Code is as follows:
<! -- The contents of this file will be loaded for each web application -->
<Context>
<! -- Default set of monitored resources -->
<WatchedResource> WEB-INF/web. xml </WatchedResource>
<WatchedResource> META-INF/context. xml </WatchedResource>
<! -- Uncomment this to disable session persistence resume SS Tomcat restarts -->
<! --
<Manager pathname = ""/>
-->
<Resource name = "jdbc/testdb"
Auth = "Container"
Type = "javax. SQL. DataSource"
DriverClassName = "com. mysql. jdbc. Driver"
Url = "jdbc: mysql: // localhost/mytestdb"
Username = "root"
Password = "157744375"
MaxActive = "100"
MaxIdle = "30"
MaxWait = "10000"
/>
</Context>

Note: You can use the localhost () function in the Javabean Database written in step 1 to read the jdbc/testdb name in content. xml.
Web. xml
Copy codeThe Code is as follows:
<? Xml version = "1.0" encoding = "gbk"?>
<Web-app id = "WebApp_ID" version = "2.4" 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">
<Display-name>
Test </display-name>
<Welcome-file-list>
<Welcome-file> test. jsp </welcome-file>
</Welcome-file-list>
<! -- JSPC servlet mappings start -->
<! -- JSPC servlet mappings end -->
</Web-app>

Note: The default homepage (for example, test. jsp or index. jsp) of web is stored in web. xml and the servlet ing is used in the program, no matter whether it is used here.
Step 3: Write test. jsp
Copy codeThe Code is as follows:
<% @ Page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8" %>
<% @ Page import = "java. SQL. *" %>
<% @ Page import = "withouttears. jdbc. db. *" %>
<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gbk">
<Title> Insert title </title>
</Head>
<Body>
<%
String SQL = null;
SQL = "select * from table_test ";
ResultSet rs1_database.exe cuteQuery (SQL );
Try {
While (rs. next ()){
%>
Name: <% = rs. getString ("name") %> <br>
Tel: <% = rs. getString ("mobile") %> <br>
<% }} Catch (Exception e) {}%>
</Body>
</Html>

Step 4: Test

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.