简体   繁体   中英

Sharing python MySQL connection object between python classes

Using python's MySQLdb I connect to database and fetch different values.

Main class needs number of values from database. To get this values, I am writing separate classes. But in every class, I again need different values from db. So again I need to make connection to database and fetching values. This doesn't seem elegant solution.

1) What is the best approach to share mysql connection between classes? Something more generic than passing connection instance directly or any well known pattern for such kind of situation?

2) Do we need new cursor object for each query? Or single one is sufficient.

Update: How it goes if I use singleton or borg pattern to create only one instance of connection. or do I give shot to ORM like sqlalchemy?

Consider following eg. 'Main' class depends on 'Foo' and 'Bar'. All of three needs to connect db for some values.

class Bar(object):
    def __init__(self):
        self.host = "127.0.0.1"
    self.username = 'foo'
    self.passwd = 'bar'
    self.dbname = 'foobar'

    def getAge(self, id, name):
        query = ...
        conn = MySQLdb.connect(self.host, self.username, self.passwd, self.dbname)
        cursor = conn.cursor()
        cursor.excute(query)
        result = cursor.fetchone()
        age = result[0]
        cursor.close()
        del cursor
        conn.close()
        return age 


class Foo(object):
    def __init__(self):
        self.host = "127.0.0.1"
    self.username = 'foo'
    self.passwd = 'bar'
    self.dbname = 'foobar'

    def getName(self, id):
        query = ...
        conn = MySQLdb.connect(self.host, self.username, self.passwd, self.dbname)
        cursor = conn.cursor()
        cursor.excute(query)
        result = cursor.fetchone()
        name = result[0]
        cursor.close()
        del cursor
        conn.close()
        return name 


class Main(object):
    def __init__(self):
        self.host = "127.0.0.1"
    self.username = 'foo'
    self.passwd = 'bar'
    self.dbname = 'foobar'

    def connect(self):
        self.conn = MySQLdb.connect(self.host, self.username, self.passwd, self.dbname)

    def getId(self):
        query = ...
        cursor = self.conn.cursor()
        cursor.excute(query)
        result = cursor.fetchone()
        name = result[0]
        cursor.close()
        del cursor
        return id 

    def process(self):
        self.connect()
        id = self.getId()
        name = Foo().getName(id)
        age = Bar().getAge(id, name)
        self.conn.close()
        print id, name, age

Thanks in advance.

You can make a db class which has a self.dbconn = MySQLdb.connect(...) as a member and make it answer the queries for Age, Name etc. So then you use the same dbconn object for all your queries. You can also reuse cursor objects for different queries.

To be really perfect, you can also specify a del method on the db class to close the connection on destruction. (Check also this discussion )

You are just repeating the same piece of code in every class. You can either create a base class to encapsulate the query connection plumbing and execution logic and use this method(inheritance). Or, create a separate class containing the logic and use an instance of it(composition).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM