Java Database Connection pooling technology is simple to use

Source: Internet
Author: User

Tag:j2ee    database connection pool    

JDBCDemo.java:package Com.itheima.jdbc;import Java.sql.connection;import Java.sql.preparedstatement;import Java.sql.resultset;import Java.sql.sqlexception;import Com.itheima.pool.mypool;public class JDBCDemo {public static void Main (string[] args) {Connection conn = null; PreparedStatement PS = null; ResultSet rs = null; Mypool pool = new Mypool (), try {conn = pool.getconnection ();p s = conn.preparestatement ("SELECT * from Account"); rs = Ps.ex Ecutequery (); while (Rs.next ()) {String name = rs.getstring (2); String salary = rs.getstring (3); SYSTEM.OUT.PRINTLN (name + ":" + Salary);}} catch (Exception e) {e.printstacktrace (); throw new RuntimeException (e);} finally {//Close database connection if (rs! = null) {try {rs.close ( );} catch (SQLException e) {rs = null;}} if (PS! = null) {try {ps.close ();} catch (SQLException e) {PS = null;}} /*if (rs! = null) {try {rs.close ();} catch (SQLException e) {rs = null;}} *///cannot close the database connection object connection, it should be returned to the database connection pool POOL.RETURNCONN (conn);}}

Mypool.java:

Package Com.itheima.pool;import Java.io.printwriter;import Java.sql.connection;import Java.sql.DriverManager; Import Java.sql.sqlexception;import Java.sql.sqlfeaturenotsupportedexception;import Java.util.LinkedList;import Java.util.list;import Java.util.logging.logger;import Javax.sql.datasource;public class MyPool implements DataSource {//list collection saves Connection objects in the database connection pool private static list<connection> pool = new linkedlist<connection> ();// A static block of code that initializes the list collection, which initializes the database connection pool, creates 5 connection objects to save for use with static {try {Class.forName ("Com.mysql.jdbc.Driver"); for (int i = 0; I < 5; i++) {Connection conn = drivermanager.getconnection ("Jdbc:mysql://localhost:3306/day11", "root", "root");p Ool.add ( conn);}} catch (ClassNotFoundException e) {e.printstacktrace (); throw new RuntimeException (e);} catch (SQLException e) { E.printstacktrace (); throw new RuntimeException (e);}} @Overridepublic PrintWriter Getlogwriter () throws SQLException {return null;} @Overridepublic void Setlogwriter (PrintWriter out) throwsSQLException {} @Overridepublic void setlogintimeout (int seconds) throws SQLException {} @Overridepublic int Getlogintimeout () throws SQLException {return 0;} @Overridepublic Logger Getparentlogger () throws sqlfeaturenotsupportedexception {return null;} @Overridepublic <T> T Unwrap (class<t> iface) throws SQLException {//TODO auto-generated method Stubreturn nul l;} @Overridepublic boolean iswrapperfor (class<?> iface) throws SQLException {//TODO auto-generated method Stubreturn false;} Overrides the Getconnection () method of the parent class to return a connection object in the database connection pool,//If the connection object in the database connection pool is already in use, it is taken away and not returned. Then create 3 Connection objects to save them for later use @overridepublic Connection getconnection () throws SQLException {if (pool = = null) {for (int i = 0 ; I < 3; i++) {Connection conn = drivermanager.getconnection ("Jdbc:mysql://localhost:3306/day11", "root", "root");p Ool.add ( conn);}} Return Pool.remove (0);} Creates a new method that returns the database connection object Connection, because the DAO layer should not be destroyed after the database connection is exhausted, but should be returned to the database connection pool public void Returnconn (Connection conn) { POOL.ADD (conn);} @OverRidepublic Connection getconnection (string Username, string password) throws SQLException {//TODO auto-generated method s Tubreturn null;}}

The above code is a simple use of database connection pooling, but one problem is that when you use database connection pooling technology, you need to modify the code in the finally code block in the Jdbcdemo.java file, that is, the Conn object should not pass through the Conn.close in the finally block. Method is closed, but should be returned to the database connection pool. Here we use the "dynamic proxy" approach to solve the problem, that is, the finally code block still calls Conn.close ();

At this point the code for the above two Java files is changed as follows:

package Com.itheima.jdbc;import Java.sql.connection;import Java.sql.preparedstatement;import Java.sql.ResultSet;import Java.sql.sqlexception;import Com.itheima.pool.mypool;public class Jdbcdemo {public static void main (string[] args) { Connection conn = null; PreparedStatement PS = null; ResultSet rs = null; Mypool pool = new Mypool (), try {conn = pool.getconnection ();p s = conn.preparestatement ("SELECT * from Account"); rs = Ps.ex Ecutequery (); while (Rs.next ()) {String name = rs.getstring (2); String salary = rs.getstring (3); SYSTEM.OUT.PRINTLN (name + ":" + Salary);}} catch (Exception e) {e.printstacktrace (); throw new RuntimeException (e);} finally {//Close database connection if (rs! = null) {try {rs.close ( );} catch (SQLException e) {rs = null;}} if (PS! = null) {try {ps.close ();} catch (SQLException e) {PS = null;}} IF (conn! = null) {try {conn.close ();} catch (SQLException e) {conn = null;}}}} 
Package Com.itheima.pool;import Java.io.printwriter;import Java.lang.reflect.invocationhandler;import Java.lang.reflect.method;import Java.lang.reflect.proxy;import Java.sql.connection;import Java.sql.DriverManager; Import Java.sql.sqlexception;import Java.sql.sqlfeaturenotsupportedexception;import Java.util.LinkedList;import Java.util.list;import Java.util.logging.logger;import Javax.sql.datasource;public class MyPool implements DataSource {//list collection saves Connection objects in the database connection pool private static list<connection> pool = new linkedlist<connection> ();// A static block of code that initializes the list collection, which initializes the database connection pool, creates 5 connection objects to save for use with static {try {Class.forName ("Com.mysql.jdbc.Driver"); for (int i = 0; I < 5; i++) {Connection conn = drivermanager.getconnection ("Jdbc:mysql://localhost:3306/day11", "root", "root");p Ool.add ( conn);}} catch (ClassNotFoundException e) {e.printstacktrace (); throw new RuntimeException (e);} catch (SQLException e) { E.printstacktrace (); throw new RuntimeException (e);}} @Overridepublic PrintWriter GEtlogwriter () throws SQLException {return null;} @Overridepublic void Setlogwriter (PrintWriter out) throws SQLException {} @Overridepublic void setlogintimeout (int seconds) throws SQLException {} @Overridepublic int getlogintimeout () throws SQLException {return 0;} @Overridepublic Logger Getparentlogger () throws sqlfeaturenotsupportedexception {return null;} @Overridepublic <T> T Unwrap (class<t> iface) throws SQLException {//TODO auto-generated method Stubreturn nul l;} @Overridepublic boolean iswrapperfor (class<?> iface) throws SQLException {//TODO auto-generated method Stubreturn false;} Overrides the Getconnection () method of the parent class to return a connection object in the database connection pool,//If the connection object in the database connection pool is already in use, it is taken away and not returned. Then create 3 Connection objects to save them for later use @overridepublic Connection getconnection () throws SQLException {if (pool = = null) {for (int i = 0 ; I < 3; i++) {Connection conn = drivermanager.getconnection ("Jdbc:mysql://localhost:3306/day11", "root", "root");p Ool.add ( conn);}} Final Connection conn = pool.remove (0);//Use dynamic Proxy to changeBuild Close method//newproxyinstance (class loader, all interfaces implemented by the Conn object to be modified, anonymous inner class) Connection proxy = (Connection) proxy.newproxyinstance ( Conn.getclass (). getClassLoader (), Conn.getclass (). Getinterfaces (), new Invocationhandler () {@Overridepublic Object Invoke (Object Proxy, Method method, object[] args) throws Throwable {if ("Close". Equals (Method.getname ())) {//If the Close method , we do rewrite returnconn (conn); return null;} else {//If it is another method, call return Method.invoke (conn, args);}}); System.out.println ("Get a Connection object, remaining Connection object:" + pool.size ()); return proxy; Creates a new method that returns the database connection object Connection, because the DAO layer should not be destroyed after the database connection is exhausted, but should be returned to the database connection pool public void Returnconn (Connection conn) { POOL.ADD (conn); System.out.println ("Return a Connection object, remaining Connection object:" + pool.size ());} @Overridepublic Connection getconnection (string Username, string password) throws SQLException {//TODO auto-generated Method Stubreturn null;}}

Operation Result:

Get a Connection object, remaining Connection object: 4a:1000.0b:1000.0c:1000.0 Returns a Connection object, remaining connection object: 5


Java Database Connection pooling technology is simple to use

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.