简体   繁体   English

在python类之间共享python MySQL连接对象

[英]Sharing python MySQL connection object between python classes

Using python's MySQLdb I connect to database and fetch different values. 使用python的MySQLdb,我连接到数据库并获取不同的值。

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. 但是在每个类中,我再次需要与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? 1)在类之间共享mysql连接的最佳方法是什么? 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? 2)每个查询是否都需要新的游标对象? Or single one is sufficient. 或单一个就足够了。

Update: How it goes if I use singleton or borg pattern to create only one instance of connection. 更新:如果我使用单例或borg模式仅创建一个连接实例,该如何进行。 or do I give shot to ORM like sqlalchemy? 还是像sqlalchemy一样给ORM开枪?

Consider following eg. 考虑以下。 'Main' class depends on 'Foo' and 'Bar'. “主要”类取决于“ Foo”和“ Bar”。 All of three needs to connect db for some values. 所有这三个需要连接db以获得某些值。

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. 您可以创建一个具有self.dbconn = MySQLdb.connect(...)作为成员的db类,并使其回答有关Age,Name等的查询。因此,对于所有查询都使用相同的dbconn对象。 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. 确实,您还可以在db类上指定一个del方法来关闭销毁连接。 (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). 或者,创建一个单独的包含逻辑的类,并使用它的一个实例(组成)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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