Python Database connection Pool dbutils

Source: Internet
Author: User
Tags connection pooling set time

Dbutils is a Python module that implements database connection pooling.

There are two modes of connection for this connection pool:

  • Mode one: Creates a connection for each thread, and the thread does not close even if the Close method is called, but simply puts the connection back into the connection pool for its own thread to use again. When the thread terminates, the connection is automatically closed.
  • POOL =Persistentdb (creator=pymysql,#modules that use linked databasesMaxusage=none,#the maximum number of times a link is reused, none means unlimitedSetsession=[],#a list of commands to execute before starting the session. such as: ["Set Datestyle to ...", "Set time zone ..."]ping=0,#Ping the MySQL server to check if the service is available. # for example: 0 = None = never, 1 = default = Whenever it is requested, 2 = When a cursor is created, 4 = When a query is executed, 7 = Alwayscloseable=False,#If False, Conn.close () is actually ignored for the next use, and the link is automatically closed when the thread is closed. If True, Conn.close () closes the link, and then calls Pool.connection again with an error, because the connection is actually closed (pool.steady_connection () can get a new link)Threadlocal=none,#This thread is exclusive to the object that holds the linked object, if the linked object is resethost='127.0.0.1', Port=3306, the user='Root', Password='123', Database='Pooldb', CharSet='UTF8')deffunc (): Conn= Pool.connection (shareable=False) Cursor=conn.cursor () cursor.execute ('SELECT * from TB1') Result=Cursor.fetchall () cursor.close () Conn.close () func ()
    View Code
  • Mode two: Create a batch of connections to the connection pool for all threads to share with.
    PS: Because the threadsafety value of Pymysql, MYSQLDB, etc. is 1, the threads in this mode connection pool are shared by all threads.
  • Import TimeImportPymysqlImportThreading fromDbutils.pooleddbImportPooleddb, Shareddbconnectionpool=Pooleddb (creator=pymysql,#modules that use linked databasesMaxconnections=6,#the maximum number of connections allowed for a connection pool, 0 and none means no limit on the number of connectionsmincached=2,#at least 0 of the free links created in the link pool are not created when initializingMaxcached=5,#most idle links in the link pool, 0 and none are not limitedMaxshared=3,#The maximum number of links shared in a linked pool, 0 and none means sharing all. PS: Useless, because Pymysql and mysqldb modules such as threadsafety are 1, all values regardless of set to how much, _maxcached forever is 0, so forever is all links are shared. Blocking=true,#If there are no available connections in the connection pool, wait is blocked. True, wait, False, not wait and then errorMaxusage=none,#the maximum number of times a link is reused, none means unlimitedSetsession=[],#a list of commands to execute before starting the session. such as: ["Set Datestyle to ...", "Set time zone ..."]ping=0,#Ping the MySQL server to check if the service is available. # for example: 0 = None = never, 1 = default = Whenever it is requested, 2 = When a cursor is created, 4 = When a query is executed, 7 = Alwayshost='127.0.0.1', Port=3306, the user='Root', Password='123', Database='Pooldb', CharSet='UTF8')deffunc ():#detects if the number of currently running connections is less than the maximum number of links, if not less than: Waits or reports raise Toomanyconnections exception    #otherwise    #gets the link steadydbconnection in the link created when the initialization is prioritized.     #The Steadydbconnection object is then encapsulated into the pooleddedicateddbconnection and returned.     #if the link you initially created is not linked, create a Steadydbconnection object and encapsulate it in pooleddedicateddbconnection and return.     #once the link is closed, the connection is returned to the connection pool for subsequent threads to continue to use. conn =pool.connection ()#print (th, ' link was taken away ', Conn1._con)    #print (Th, ' currently in the pool ', Pool._idle_cache, ' \ r \ n ')cursor=conn.cursor () cursor.execute ('SELECT * from TB1') Result=Cursor.fetchall () conn.close () func ()
    View Code

    If there is no connection pool, using Pymysql to connect to the database, single-threaded application is completely no problem, but if it involves multi-threaded application then need to lock, once the lock then the connection will be queued, when the request more time, performance will be reduced.

  • #!/usr/bin/env python#-*-coding:utf-8-*-ImportPymysqlImportThreading fromThreadingImportRlocklock=rlock () CONN= Pymysql.connect (host='127.0.0.1', Port=3306, the user='Root', Password='123', Database='Pooldb', CharSet='UTF8')defTask (ARG): With Lock:cursor=conn.cursor () cursor.execute ('SELECT * from TB1') Result=Cursor.fetchall () cursor.close ( )Print(Result) forIinchRange (10): T= Threading. Thread (Target=task, args=(i,)) T.start () locking
    Locking
    #!/usr/bin/env python#-*-coding:utf-8-*-ImportPymysqlImportThreadingconn= Pymysql.connect (host='127.0.0.1', Port=3306, the user='Root', Password='123', Database='Pooldb', CharSet='UTF8')defTask (ARG): Cursor=conn.cursor () cursor.execute ('SELECT * from TB1') Result=Cursor.fetchall () cursor.close ( )Print(Result) forIinchRange (10): T= Threading. Thread (Target=task, args=(i,)) T.start () no Lock (Error)
    no Lock (Error)

Python Database connection Pool dbutils

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.