JDBC Custom database connection pool __ Database

Source: Internet
Author: User
Tags connection pooling stmt stub

Database connectivity is a critical, limited and expensive resource, especially in multi-user Web applications. The management of database connections can significantly affect the scalability and robustness of the entire application, Affects the performance metrics of the program. The database connection pool is formally addressed to this issue. The database connection pool is responsible for allocating, managing, and freeing the database connection, which allows the application to reuse an existing database connection rather than re-establish one. without using open source database connection pools such as c3p0, we tried to use a custom database connection pool to understand the principle of the JDBC connection pool and its functional role.

several steps to customize a connection pool implementation :
1. Create database connection class Jdbcutils.
2. Create the class myDataSource class to implement the DataSource interface, the steps under this class include:
1 batch implementation of the database connection, and the creation of the connection into the linklist (because to be added and deleted operations, linklist than ArrayList performance is much higher);
2 implementation of the Getconnection method, so that the Getconnection method each time the call, from the LinkedList to fetch a Connection back to the user, 3 in the class to create a method Addbacktopool (Connection con , and then reconnect the connection back into the connection pool when the user finishes using it.
3. Write test class for testing
The specific code is as follows:

database Connection Class -by reading configuration information from the configuration file properties file, the configuration file does not enumerate

Package com.mystore.utils;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;
Import java.sql.Statement;

Import Java.util.ResourceBundle; /** * Provides database connection pooling and database connection * method is static through type Access * @author HUHONGDA * * */public class Jdbcutils {private static String Dr
    Ivername = null;
    private static String Url=null;
    private static String userName = null;
    private static String userpwd =null;
         Read content in configuration file//static method block static{ResourceBundle bundle = Resourcebundle.getbundle ("DataBase");
         drivername = bundle.getstring ("drivername");
         url = bundle.getstring ("url");
         Username= bundle.getstring ("UserName");
    Userpwd = bundle.getstring ("Userpwd");
            //Establish connection public static Connection getconnection () {try {//Register driver Loaddriver ();
            SYSTEM.OUT.PRINTLN ("Create connection succeeded");

 Establishes the connection and returns return Drivermanager.getconnection (URL, userName, userpwd);       catch (Exception e) {//Todo:handle Exception e.printstacktrace ();
    return null;
        }//Register driver public static void Loaddriver () {try {class.forname (drivername);
        catch (Exception e) {//Todo:handle Exception e.printstacktrace ();
        }//Release resources public static void release (ResultSet rs,statement stat,connection con) {//When a connection or result set is released
            if (rs!=null) {try {rs.close ();
        The catch (Exception e) {//Todo:handle Exception} rs= null;
            } if (Stat!=null) {try {stat.close ();
        The catch (Exception e) {//Todo:handle Exception} stat = null;
            } if (Con!=null) {try {con.close (); catch (Exception e) {//Todo:handleexception} con = null;
 }
    }
}

Connection Pool class

Package DataSource;
Import Java.io.PrintWriter;
Import java.sql.Connection;
Import java.sql.SQLException;

Import java.util.LinkedList;

Import Javax.sql.DataSource;
Import Com.mystore.utils.JdbcUtils; Simple implementation of custom connection pool public class myDataSource implements DataSource {//through linklist as pool private linkedlist<connectio
    N> pool = new linkedlist<connection> ();
        Constructor initializes the number of connections public myDataSource () {System.out.println ("constructor creates 20 connections");
            for (int i = 0; i < i++) {//create connection Connection Connection = Jdbcutils.getconnection ();
        Put the created connection into the pool Pool.add (connection);
    Post the passed connection back into the pool with the public void Addbacktopool (Connection Connection) {pool.add (Connection);
        @Override public PrintWriter Getlogwriter () throws SQLException {//TODO auto-generated method stub
    return null; @Override public void Setlogwriter (PrintWriter out) throws Sqlexception {//TODO auto-generated method stub} @Override public void setlogintimeout (int seconds Throws SQLException {//TODO auto-generated method stub} @Override public int getlogintimeout ()
    Throws SQLException {//TODO auto-generated method stub return 0; @Override public <T> T Unwrap (class<t> iface) throws SQLException {//TODO auto-generated
    Method stub return null; @Override public boolean iswrapperfor (Class<?> iface) throws SQLException {//TODO auto-generate
    D method stub return false; ///Get the first @Override public Connection getconnection () from the thread pool () throws SQLException {//TODO Auto-gene
                    Rated method Stub//first to determine whether to be empty if (Pool.isempty ()) {//To continue creating 5 connections for (int i = 0; i < 5; i++) {Connection Connection = jdbcutils.geTconnection ();
                    Pool.add (connection);
                If there is a connection, remove the first Connection con = Pool.removefirst ();
                SYSTEM.OUT.PRINTLN ("Obtain a connection use");
    return con;
        @Override Public Connection getconnection (string Username, string password) throws SQLException {
    TODO auto-generated method stub return null;
 }

}

simple test class

Package DataSource;
Import java.sql.Connection;
Import java.sql.PreparedStatement;

Import Java.sql.ResultSet;

Import Com.mystore.utils.JdbcUtils; Test public class Testdatasource {/** * @param args/public static void Main (string[) for a custom connection pool args
        {//TODO auto-generated method stub Connection Connection = null;
        PreparedStatement stmt = null;
        myDataSource ds = null;
        ResultSet RS =null;
            try {ds = new myDataSource ();
            Get the connection connection = Ds.getconnection () from the connection pool;
            stmt = connection.preparestatement ("update users set Passward = ' 123 ' where username=?");
            Set the value of the placeholder stmt.setstring (1, "Huhongda");

        Implementation of Stmt.executeupdate ();
        catch (Exception e) {//Todo:handle Exception e.printstacktrace ();
          }finally{//Finally put the connection back into the connection pool ds.addbacktopool (connection);  System.out.println ("Put the connection back into the connection pool after use");
        Releasing the resource does not release the connection jdbcutils.release (RS, stmt, null);
 }

    }

}

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.