簡體   English   中英

單例數據庫連接

[英]singleton database connection

我想從數據庫“詳細信息”中檢索值,因為我只想與DB建立一個連接,如果連接不存在,則不進行新連接並繼續上一個連接。 為此,我嘗試了以下操作:

import MySQLdb
import re
import os

class Find:

    def __init__(self,addr):
        self.addr = addr


    dsn = {
    'username': 'xyz',
    'password': 'xyz',
    'hostname': 'localhost',
    'database': 'details'
    }
    the_database_connection = False

    def connect(self,dsn):
        '''This function saves the database connection, so if invoke this again, it gives you the same one, rather than making a second connection.'''
        global the_database_connection
        if not the_database_connection:
            try:
                the_database_connection = MySQLdb.connect(
                    host=dsn['hostname'],
                    user=dsn['username'],
                    passwd=dsn['password'],
                    db=dsn['database'])
            # so modifications take effect automatically
                the_database_connection.autocommit(True)
            except MySQLdb.Error, e:
                print ("Couldn't connect to database. MySQL error %d: %s" %(e.args[0], e.args[1]))
        return the_database_connection
        x=conn.cursor()
        sql = "select * from persons where address = %s" % addr
        x.execute(sql)
        rows = x.fetchall()
        for row in rows:
            print row

if __name__ == "__main__":
    a = Find(addr = "new street")
    a.connect()

但這顯示了錯誤:a.connect接受2個參數,一個是define ...我如何定義上述dsn。

您正在嘗試重新創建連接池。

不幸的是,您的解決方案無法按原樣工作。 僅當所有連接參數(主機,端口,數據庫,用戶名,密碼)完全相同時,才可以使用相同的連接。 在任何情況下,無論如何您都返回相同的連接,這完全是錯誤的-如果任何屬性不同,則必須創建新連接。

相反,只需使用現有的連接池庫之一,例如pysqlpoolDBUtils (我敢肯定還有其他庫)。

您沒有按要求向a.connect函數提供dsn信息。 將dsn信息從類中拉出,並將其作為main函數的一部分。 然后將其作為a.connect的參數反饋。 像這樣:

import MySQLdb
import re
import os

class Find:

    def __init__(self,addr):
        self.addr = addr

    def connect(self,dsn):
        '''This function saves the database connection, so if invoke this again, it     gives you the same one, rather than making a second connection.'''
        global the_database_connection
        if not the_database_connection:
            try:
                the_database_connection = MySQLdb.connect(
                    host=dsn['hostname'],
                    user=dsn['username'],
                    passwd=dsn['password'],
                    db=dsn['database'])
                # so modifications take effect automatically
                the_database_connection.autocommit(True)
            except MySQLdb.Error, e:
                print ("Couldn't connect to database. MySQL error %d: %s" %(e.args[0], e.args[1]))
        return the_database_connection
        x=conn.cursor()
        sql = "select * from persons where address = %s" % addr
        x.execute(sql)
        rows = x.fetchall()
        for row in rows:
            print row

if __name__ == "__main__":
    a = Find(addr = "new street")
    dsn = {
    'username': 'xyz',
    'password': 'xyz',
    'hostname': 'localhost',
    'database': 'details'
    }
    the_database_connection = False
    a.connect(dsn)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM