Connect Database methods

Source: Internet
Author: User
Tags connection pooling

1.Driver

     PublicConnection getconnection ()throwsException {String Driverclass=NULL; String Jdbcurl=NULL; String User=NULL; String Password=NULL; //read the Jdbc.properties file under the ClasspathInputStream in = GetClass (). getClassLoader (). getResourceAsStream ("Jdbc.properties"); Properties Properties=NewProperties ();        Properties.load (in); Driverclass= Properties.getproperty ("Driver"); Jdbcurl= Properties.getproperty ("Jdbcurl"); User= Properties.getproperty ("User"); Password= Properties.getproperty ("Password"); //by reflecting common Driver objects.Driver Driver =(Driver) class.forname (Driverclass). Getdeclaredconstructor (). newinstance (); Properties Info=NewProperties (); Info.put ("User", user); Info.put ("Password", password); //get the database connection through the Driver Connect method.Connection Connection =Driver.connect (Jdbcurl, info); returnconnection; }

Jdbc.properties:

Driver=com.mysql.jdbc.driver
Jdbcurl=jdbc:mysql://localhost:3306/mysql
User=root
password=1234

2.DriverManager

 PublicConnection GetConnection2 ()throwsException {//1. Prepare 4 strings to connect to the database. //1). Create a Properties objectProperties Properties =NewProperties (); //2). Gets the input stream corresponding to the Jdbc.propertiesInputStream in = This. GetClass (). getClassLoader (). getResourceAsStream ("Jdbc.properties"); //3). Load 2) corresponding input streamproperties.load (in); //4). Specifically determine the user, password, etc. 4 strings.String user = Properties.getproperty ("User"); String Password= Properties.getproperty ("Password"); String Jdbcurl= Properties.getproperty ("Jdbcurl"); String Driver= Properties.getproperty ("Driver"); //2. Load the database driver (the corresponding Driver implementation class has a registered-driven static code block.)
Load Driver Method http://www.cnblogs.com/chenshaogang/p/8996942.htmlClass.forName (driver); //3. Get the database connection through the DriverManager getconnection () method. returndrivermanager.getconnection (jdbcurl, user, password); }

3.C3P0 Database Connection Pool

Private Static New Combopooleddatasource ("helloc3p0"= Datasource.getconnection ();

C3p0-config.xml

<?XML version= "1.0" encoding= "UTF-8"?><C3p0-config>    <Named-configname= "Helloc3p0">                <!--specifying the basic properties of a connected data source -        < Propertyname= "User">Root</ Property>        < Propertyname= "Password">1993</ Property>        < Propertyname= "Driverclass">Com.mysql.jdbc.Driver</ Property>        < Propertyname= "Jdbcurl">Jdbc:mysql:///test</ Property>                <!--How many connections are requested to the database server at a time if the number of connections in the database is insufficient -        < Propertyname= "Acquireincrement">5</ Property>        <!--number of connections when initializing a database connection pool -        < Propertyname= "Initialpoolsize">5</ Property>        <!--minimum number of database connections in the database connection pool -        < Propertyname= "Minpoolsize">5</ Property>        <!--Maximum number of database connections in a database connection pool -        < Propertyname= "Maxpoolsize">10</ Property>        <!--c3p0 The number of Statement that a database connection pool can maintain -        < Propertyname= "Maxstatements">20</ Property>        <!--The number of Statement objects that can be used at the same time for each connection -        < Propertyname= "Maxstatementsperconnection">5</ Property>        </Named-config>        </C3p0-config>

4.DBCP Database Connection Pool

Newthis. class. getClassLoader (). getResourceAsStream ("dbcp.properties"=  Basicdatasourcefactory.createdatasource (properties);d atasource.getconnection ();

Dhcp.properties:

Username=root
password=1234
Driverclassname=com.mysql.jdbc.driver
Url=jdbc:mysql:///test

initialsize=10
Maxactive=50
Minidle=5
maxwait=5000

I. The need for a JDBC database connection pool

When using the development of a database-based Web program, the traditional pattern is basically the following steps:

The ① establishes a database connection in the main program, such as servlet, beans.
② for SQL operations
③ Disconnect the database.

This pattern of development, the existence of the problem:

① the normal JDBC database connection is obtained using DriverManager, each time a connection is made to the database, the Connection is loaded into memory, and the user name and password (which takes 0.05s~1s time) are verified. When a database connection is required, a request is made to the database and then disconnected after execution is complete. Such a way would consume a lot of resources and time. Database connection resources are not well reused. If there are hundreds of or even thousands of people online, frequent database connection operations will consume a lot of system resources, which can even cause the server to crash.
② every time a database connection is used, it must be disconnected. Otherwise, if the program fails to close, it will cause a memory leak in the database system and will eventually cause the database to be restarted.
③ This development does not control the number of connection objects being created, and system resources are allocated without consideration, such as too many connections, which can lead to memory leaks and server crashes.

Second, database connection pool (connection pools) database connection pool Simple Introduction

In order to solve the problem of database connection in traditional development, database connection pool technology can be adopted.

The basic idea of a database connection pool is to establish a "buffer pool" for database connections. A certain number of connections are pre-placed in the buffer pool, and when a database connection needs to be established, simply take one out of the buffer pool and put it back when you are finished.

Database connection pooling is responsible for allocating, managing, and freeing database connections, which allows applications to reuse an existing database connection instead of re-establishing one.

When the database connection pool is initialized, a certain number of database connections are created in the connection pool, and the number of these database connections is set by the minimum number of database connections. Regardless of whether these database connections are being used, the connection pool will always be guaranteed to have at least so many connections. The maximum number of database connections for a connection pool limits the maximum number of connections that this pool can occupy, and these requests are added to the wait queue when the number of connections requested by the application to the connection pool exceeds the maximum number of connections.

How database connection pooling works:

Benefits of database connection pooling technology Resource reuse:

① due to the reuse of database connections, it avoids the high performance overhead caused by frequent creation and release of connections. On the basis of reducing the system consumption, on the other hand, it also increases the stability of the system operating environment.

  Faster system response Speed:
Database connection pooling during initialization, several database connections are often created to be placed in the connection pool for backup. The initialization of the connection is now complete. For business request processing, direct utilization of existing available connections avoids the time overhead of database connection initialization and release, thus reducing system response time

  New means of resource allocation:
For multiple applications sharing the same database system, the application layer can be configured through the database connection pool, the application of a maximum number of available database connections limit, to avoid an application exclusive all database resources

  Unified connection management to avoid database connection leaks:
In a more complete database connection pool implementation, it is possible to forcibly reclaim the occupied connection based on a pre-occupied timeout setting, thus avoiding the potential for resource leaks in regular database connection operations

Connect Database methods

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.