JDBC Application Advanced (Combined DBConnectionManager and DbconnectionPool) in Servlet

xiaoxiao2021-03-06  111

Now we combine DBConNetionManager and DBConnectionPool classes to explain the use of connecting pools in the servlet:

First, first briefly introduce the life cycle of the servlet:

The servlet lifecycle defined by the servlet API is as follows:

1. Servlet is created and then initialized (INIT () method).

2, provide a service for 0 or more customer calls (Service () method).

3, servlet is destroyed, the memory is reclaimed (the destroy () method).

Second, the instance of the connection pool in the servlet

The typical performance of the servlet using the connection pool is:

1. In init (), call dbconnectionManager.getInstance () and save the returned reference in the instance variable.

2. In Sevice (), call getConnection (), perform a series of database operations, and then call freeConnection () to return the connection.

3. In DESTROY (), Release () is called to release all resources and close all connections.

The following example demonstrates how to use the connection pool.

Import java.io. *;

Import java.sql. *;

Import javax.servlet. *;

Import javax.servlet.http. *;

Public class testservlet extends httpservlet {

Private DBConnectionManager Connmgr;

Public void init (servletconfig conf) throws servletexception {

Super.init (conf);

CONNMGR = dbconnectionmanager.getinstance ();

}

Public Void Service (httpservletRequest Req, httpservletResponse res)

THROWS IOEXCEPTION {

Res.SetContentType ("text / html");

PrintWriter out = res. maxwriter ();

Connection con = connmgr.getConnection ("iDB");

IF (con == null) {

Out.println ("CANT GET Connection");

Return;

}

ResultSet RS = NULL;

ResultSetMetAdata MD = NULL;

Statement Stmt = NULL;

Try {

STMT = con.createstatement ();

RS = stmt.executeQuery ("Select * from Employee);

MD = rs.getMetadata ();

Out.println ("

Employee Data

");

While (rs.next ()) {

Out.println ("

");

For (int i = 1; i

Out.print (rs.getstring (i) ",")

}

}

Stmt.close ();

Rs.close ();

}

Catch (SQLException E) {

E.PrintStackTrace (OUT);

}

Connmgr.FreeConnection ("iDB", con);

}

Public void destroy () {

CONNMGR.RELEASE ();

Super.destroy ();

}

}

转载请注明原文地址:https://www.9cbs.com/read-97544.html

New Post(0)