Simple use of three common connection pools.

Source: Internet
Author: User

Simple use of three common connection pools.

Simple use of three common connection pools

C3p0:

Currently, c3p0 is widely used in connection pools. Many frameworks use c3p0 as a connection pool for database connection.

So how can we use c3p0 to obtain the connection,

C3p0 provides three methods

1. setting properties through setXXX () is very simple, but in this case, hard encoding is inevitable (spring framework can set attributes in the spring configuration file through dependency injection)

2. Configure the properties file. In this way, create a c3p0 directly. properties file and set the corresponding properties. c3p0 can be automatically parsed (so you need to modify the source code when modifying the connection properties)

3. Configure information through the xml file, which is similar to the second point. In addition, the xml configuration file seems to be used more.

For details, refer to http: // blog.csdn.net/u012506661/article/details/53548083.

Next we will attach the code of the first method, which is the simplest to use and does not need to be configured. It is the same as what I wrote last time, I have encapsulated it into a DBUtil tool class,

Step 1.

Import jar package

 

Step 2: instantiate a ComboPooledDataSource object and Set properties (I created a properties file for configuration)

Step 3. Call getConnection () to obtain the connection.

1 package com. c3p0; 2 3 import java. beans. propertyVetoException; 4 import java. SQL. connection; 5 import java. SQL. driverManager; 6 import java. SQL. preparedStatement; 7 import java. SQL. resultSet; 8 import java. SQL. SQLException; 9 import java. util. resourceBundle; 10 11 import com. mchange. v2.c3p0. comboPooledDataSource; 12 13 14 public class DButil {15 private static combooleddatasource ds = null; 16 ResultSet rs = null; 17 Connection con = null; 18 PreparedStatement stmt = null; 19 static {20 ds = new ComboPooledDataSource (); 21 try {22 ds. setDriverClass ("com. mysql. jdbc. driver "); 23} catch (PropertyVetoException e) {24 // TODO Auto-generated catch block 25 e. printStackTrace (); 26} 27 ResourceBundle rb = ResourceBundle. getBundle ("dbcp"); 28 ds. setJdbcUrl (rb. getString ("url"); 29 ds. setUser (rb. GetString ("name"); 30 ds. setPassword (rb. getString ("password"); 31 ds. setMaxPoolSize (Integer. parseInt (rb. getString ("maxActive"); // sets the maximum number of connections to 32 ds. setMaxIdleTime (Integer. parseInt (rb. getString ("maxWait"); // sets the wait time to 33 ds. setInitialPoolSize (Integer. parseInt (rb. getString ("maxIdle"); // set the maximum number of idle connections 34} 35 // use the constructor to load the drive 36 public DButil () {37 38} 39 40 // create a link object 41 public void conManager () 42 {43 try {44 con = ds. getConnection (); 45} catch (SQLException e) {46 // TODO Auto-generated catch block 47 e. printStackTrace (); 48} 49} 50 // Method for disabling database 51 public void closeFunction (ResultSet rs) {52 try {53 // disable 54 if (rs! = Null) {55 rs. close (); 56} 57 if (con! = Null) {58 ds. close (); 59} 60 if (stmt! = Null) {61 stmt. close (); 62} 63} catch (Exception e) {64 e. printStackTrace (); 65} 66} 67/** 68 * methods used to encapsulate the tool class (for addition, deletion, and modification) 69 * @ param SQL 70 * @ return 71 */72 public int execUpdate (String SQL, Object [] o) {73 int result = 0; 74 // create a Conn type variable 75 try {76 conManager (); 77 // create a database operation object 78 79 stmt = con. prepareStatement (SQL); 80 if (o! = Null) {81 for (int I = 0; I <o. length; I ++) {82 stmt. setObject (I + 1, o [I]); 83} 84} 85 // Save the database with result and execute 86 result1_stmt.exe cuteUpdate (); 87} catch (Exception e) {88 e. printStackTrace (); 89} 90 finally {91 closeFunction (null); 92} 93 94 95 return result; 96} 97/** 98 * encapsulation tool class for querying 99 */100 public ResultSet connectionSelect (String SQL, Object [] o) {101 try {102 // write driver 103 conManager (); 104 // create database operation object 105 stmt = Con. prepareStatement (SQL); 106 if (o! = Null) {107 for (int I = 0; I <o. length; I ++) {108 stmt. setObject (I + 1, o [I]); 109} 110} 111 // use rs to save the database and execute 112 rs1_stmt.exe cuteQuery (); 113 114 115} catch (Exception e) {116 e. printStackTrace (); 117} 118 return rs; 119} 120}
View Code
package com.c3p0;import java.sql.ResultSet;import org.junit.Test;public class Demo {@Testpublic void run() throws Exception{DButil db = new DButil();ResultSet rs = db.connectionSelect("select * from SECURITY",null);while(rs.next()){System.out.println(rs.getString(1)+"\t"+rs.getString(2));}}}

  

Use of DBCP

There are also three steps

1. Import the rack package

2. instance a BasicDataSource class and set attributes

3. Obtain the connection and perform operations

1 @ Test 2 public void demo () throws Exception {3 // create a resource object 4 ResourceBundle rb = ResourceBundle. getBundle ("dbcp"); 5 // create the basic data source 6 BasicDataSource bds = new BasicDataSource (); 7 // set the parameter 8 bds. setMaxActive (Integer. parseInt (rb. getString ("maxActive"); 9 bds. setMaxIdle (Integer. parseInt (rb. getString ("maxIdle"); 10 bds. setMaxWait (Integer. parseInt (rb. getString ("maxWait"); 11 bds. setUsername (rb. getString ("name"); 12 bds. setPassword (rb. getString ("password"); 13 bds. setDriverClassName (rb. getString ("driverClassName"); 14 bds. setUrl (rb. getString ("url"); 15 16 Connection conn = bds. getConnection (); 17 PreparedStatement pst = conn. prepareStatement ("select * from SECURITY"); 18 // run sql19 ResultSet rs = pst.exe cuteQuery (); 20 // traverse 21 while (rs. next () {22 System. out. println (rs. getObject (1) + "\ t" + rs. getObject (2); 23} 24 rs. close (); 25 pst. close (); 26 conn. close (); 27}
View Code

It is worth mentioning that the druid connection pool is said to be better than any previous connection pool in terms of performance. It may not be long before, and the market of the connection pool may be dominated by druid, so this is important.

Druid also supports three connection attribute configuration methods,

That is, set Method settings, properties file configuration, and xml configuration files. As this is only a simple use, I use the first method.

The procedure is as follows:

1. Import the jar package

2. instantiate DruidDataSource and set properties using the set method.

3. Obtain the connection

4. perform operations,

5. directly call the close of the connection to return the connection.

Tool code

Public class DButil {private static DruidDataSource ds = null; ResultSet rs = null; Connection con = null; PreparedStatement stmt = null; static {// read configuration file information ResourceBundle rb = ResourceBundle. getBundle ("dbcp"); ds = new DruidDataSource (); // set the ds connection pool parameter. setDriverClassName (rb. getString ("url"); ds. setUsername (rb. getString ("name"); ds. setPassword (rb. getString ("password"); ds. setUrl (rb. getString ("url" ); Ds. setInitialSize (Integer. parseInt (rb. getString ("maxActive"); ds. setMinIdle (Integer. parseInt (rb. getString ("maxWait"); ds. setMaxActive (Integer. parseInt (rb. getString ("maxIdle");} // use the constructor to load the drive public DButil () {}// create the public void conManager () {try {con = ds. getConnection ();} catch (SQLException e) {// TODO Auto-generated catch block e. printStackTrace () ;}/// Method for disabling public void c in the database LoseFunction (ResultSet rs) {try {// disable if (rs! = Null) {rs. close () ;}if (con! = Null) {con. close () ;}if (stmt! = Null) {stmt. close () ;}} catch (Exception e) {e. printStackTrace () ;}/ *** encapsulate tool class methods (for addition, deletion, modification) * @ param SQL * @ return */public int execUpdate (String SQL, Object [] o) {int result = 0; // create the Conn type variable try {conManager (); // create the database operation object stmt = con. prepareStatement (SQL); if (o! = Null) {for (int I = 0; I <o. length; I ++) {stmt. setObject (I + 1, o [I]) ;}// use result to save the database and execute result1_stmt.exe cuteUpdate () ;} catch (Exception e) {e. printStackTrace ();} finally {closeFunction (null);} return result;}/*** encapsulation tool class for querying */public ResultSet connectionSelect (String SQL, Object [] o) {try {// write driver conManager (); // create a database operation object stmt = con. prepareStatement (SQL); if (o! = Null) {for (int I = 0; I <o. length; I ++) {stmt. setObject (I + 1, o [I]) ;}// run rs1_stmt.exe cuteQuery ();} catch (Exception e) {e. printStackTrace ();} return rs ;}}
View Code

Test code

@Test    public void run() throws Exception{        DButil db = new DButil();        ResultSet rs = db.connectionSelect("select * from user",null);        while(rs.next()){            System.out.println(rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t");        }    }
View Code

To sum up, as we said yesterday, all three connection pools require the instantiation of an implementation class that implements the DataSource interface for operations, at the same time, they enhance the close method of the connection obtained to close the connection.

Instead of closing the connection to the database, the connection pool is returned. It is not very detailed and requires more learning.

Detailed available http://www.cnblogs.com/hafiz/p/5879356.html

 

I can share an article, which is much more detailed than I have.

Http://www.cnblogs.com/shellway/p/3938554.html

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.