using one database connection across multiple functions in python

whats the best way to go about this in python? I have a number of like so

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>def test1()
.... code .....
def test2()
.... code .....
def test3()
.... code .....
</code>
<code>def test1() .... code ..... def test2() .... code ..... def test3() .... code ..... </code>
def test1()
    .... code .....
def test2()
    .... code .....
def test3()
    .... code .....

how could I create one database connection and use it across all the functions? I’m connecting to my database in a test file like so:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import MySQLdb as mdb
import sys
try:
con = mdb.connect('10.243.17.13', 'mark', '********', 'dex');
cur = con.cursor()
cur.execute("SELECT VERSION()")
ver = cur.fetchone()
print "Database version : %s " % ver
except mdb.Error, e:
print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)
</code>
<code>import MySQLdb as mdb import sys try: con = mdb.connect('10.243.17.13', 'mark', '********', 'dex'); cur = con.cursor() cur.execute("SELECT VERSION()") ver = cur.fetchone() print "Database version : %s " % ver except mdb.Error, e: print "Error %d: %s" % (e.args[0],e.args[1]) sys.exit(1) </code>
import MySQLdb as mdb
import sys

try:
    con = mdb.connect('10.243.17.13', 'mark', '********', 'dex');

    cur = con.cursor()
    cur.execute("SELECT VERSION()")

    ver = cur.fetchone()
    
    print "Database version : %s " % ver

except mdb.Error, e:

    print "Error %d: %s" % (e.args[0],e.args[1])
    sys.exit(1)

4

The problem is well known and the keyword you may be searching for is pooling.

The idea is that opening a connection is a complicated task: is usually requires reaching the server, doing authentication, checking the rights, auditing, etc.

On the other hand, preserving the same connection through the application by either storing it in a static variable or passing it to every method which may require access to the database is usually ugly and difficult to implement. Not counting the fact that in this case, the connection may remain opened for a long time while being unused, eventually reaching the maximum number of connections allowed by the server.

Connection pooling consists of preserving the pool of connections under the hood in order to make it possible for the programmer to open the connection and close it as soon as it is not needed any longer. The actual connections are managed transparently, meaning that you don’t have the overheat of a connection opened again and again and you are less at risk of using all available connections.

Further reading:

  • Opening and closing database connection for each query at Stack Overflow.

  • Pooling and performance: what benchmarks and profiling may reveal, an article from my blog.

Now, not reusing the connection doesn’t mean you should duplicate database logic in every of your tests. You may put connection and disposal logic in a class with special __enter__ and __exit__ methods, and then use it as:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>with DatabaseConnection() as db:
cursor = db.connection.cursor()
...
</code>
<code>with DatabaseConnection() as db: cursor = db.connection.cursor() ... </code>
with DatabaseConnection() as db:
    cursor = db.connection.cursor()
    ...

Note that since you mention tests in your code sample:

  1. You may be interested in using a testing framework. After all, you said that you “just play with Python, learning by doing”, so why not to learn a Python’s testing framework as well?

  2. As others noted, unit tests shouldn’t access a database. But access to databases is perfectly fine in integration or system tests.

The best thing it occurs to me it’s creating a class, so you can save the connection in an attribute, and then use it by all the test methods. In example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import sys
import MySQLdb as mdb
class MyDBTest():
def __init__(self, host, user, passw, db):
try:
self.con = mdb.connect(host, user, passw, db)
self.cur = self.con.cursor()
except mdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit(1)
def show_version(self):
self.cur.execute("SELECT VERSION()")
print "Database version : %s " % self.cur.fetchone()
def test1(self):
# Do something with self.con or self.cur
pass
def test2(self):
# Do something with self.con or self.cur
pass
if __name__ == '__main__': # If it's executed like a script (not imported)
db = MyDBTest('10.243.17.13', 'mark', 'LiverpoolFc', 'dex')
db.show_version()
db.test1()
db.test2()
</code>
<code>import sys import MySQLdb as mdb class MyDBTest(): def __init__(self, host, user, passw, db): try: self.con = mdb.connect(host, user, passw, db) self.cur = self.con.cursor() except mdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit(1) def show_version(self): self.cur.execute("SELECT VERSION()") print "Database version : %s " % self.cur.fetchone() def test1(self): # Do something with self.con or self.cur pass def test2(self): # Do something with self.con or self.cur pass if __name__ == '__main__': # If it's executed like a script (not imported) db = MyDBTest('10.243.17.13', 'mark', 'LiverpoolFc', 'dex') db.show_version() db.test1() db.test2() </code>
import sys
import MySQLdb as mdb

class MyDBTest():

    def __init__(self, host, user, passw, db):
        try:
            self.con = mdb.connect(host, user, passw, db)
            self.cur = self.con.cursor()
        except mdb.Error, e:
            print "Error %d: %s" % (e.args[0], e.args[1])
            sys.exit(1)

    def show_version(self):
            self.cur.execute("SELECT VERSION()")
            print "Database version : %s " % self.cur.fetchone()

    def test1(self):
        # Do something with self.con or self.cur
        pass

    def test2(self):
        # Do something with self.con or self.cur
        pass

if __name__ == '__main__':  # If it's executed like a script (not imported)
    db = MyDBTest('10.243.17.13', 'mark', 'LiverpoolFc', 'dex')
    db.show_version()
    db.test1()
    db.test2()

In the example I’ve put the error checking (try-except) inside the class. But you could also don’t put it in there and leave the main (__name__ == __main__ part) to handle the errors if they occurr inside MyDBTest.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật