JDBC data source and connection pool, jdbc
JDBC data source and Connection Pool
The database connection pool is used to create enough database connection pools when the application starts.
A free connection can be obtained through the data source when the database is used up and returned to the connection pool.
Instance:
In Tomcat6.0 + MySQL5.5, configure the data source and Connection Pool
(1) copy the JDBC driver of the database to the <CATALINA_HOME>/common/lib directory.
(2) configure the data source and connection pool in <CATALINA_HOME>/conf/server. xml, for example
<Context path = "/JSP_JDBC" docBase = "JSP_JDBC" debug = "0" reloadable = "true">
<ResourceParams name = "jdbc/myDataSource" auth = "Container" type = "javax. SQL. DataSource"/>
<Parameter>
<Name> factory </name>
<Value> org. apache. commons. dbcp. basicperformancefactory </value>
</Parameter>
<Parameter>
<Name> maxActive </name>
<Value> 1000 </value>
</Parameter>
<Parameter>
<Name> maxIdle </name>
<Value> 30 </value>
</Parameter>
<Parameter>
<Name> maxWait </name>
<Value> 10000 </value>
</Parameter>
<Parameter>
<Name> username </name>
<Value> root </value>
</Parameter>
<Parameter>
<Name> password </name>
<Value> root </value>
</Parameter>
<Parameter>
<Name> driverClassName </name>
<Value> com. mysql. jdbc. Driver </value>
</Parameter>
<Parameter>
<Name> url </name>
<Value> jdbc: mysql: // localhost/test? AutoReconnect = true </value>
</Parameter>
<ResourceParams>
<Context>
Configure the reference of the data source connection pool in the web. xml file
<Resource-ref>
<Description> DB Connection </description>
<Res-ref-name> jdbc/myDataSource </res-ref-name>
<Res-type> javax. SQL. DataSource </res-type>
<Res-auth> Container </res-auth>
</Resource-ref>
Access the database through the data source in jsp or Servlet
<Html>
<Head> <title> access a database from a data source </title> <Body>
Access a database through a data source
<%
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
// Obtain the connection from the data source connection pool
Context ctx = new InitialContext ();
DataSource ds = (DataSource) ctx. lookup ("java: comp/env/jdbc/myDataSource ");
Conn = ds. getConnection ();
// Query the data table
Stat = conn. createStatement ();
String SQL = "select * from user ";
Rs.stat.exe cuteQuery (SQL );
// Output the query result to the interface
While (rs. next ()){
Out. println ("<li> account:" + rs. getString (2). trim ());
Out. println ("Password:" + rs. getString (3). trim () + "</li> ");
}
// Close the connection and release resources
Rs. close ();
Stat. close ();
Conn. close ();
%>
</Body>
</Html>