我目前正在做一個巨大的專案,它不斷地執行查詢。我的問題是,我的舊代碼總是創建一個新的資料庫連接和游標,這極大地降低了速度。
class Database(object)。
_instance = None。
def __new__(cls):
if cls._instance is None:
cls._instance = object.__new__(cls)
try:
connection = Database._instance.connection = mysql.connector.connect(host="127.0.0.1"/span>, user="root"/span>, password=""/span>, database="db_test"/span>)
cursor = Database._instance.cursor = connection.cursor()
except 例外 as error:
print("錯誤。連接未建立{}".format(error))
else:
print("Connection established"/span>)
return cls._instance
def __init__(self):
self.connection = self._instance.connection
self.cursor = self._instance.cursor
# 在這里做資料庫的事情。
查詢將像這樣使用該類:
查詢將使用該類。
def foo()。
with Database() as cursor:
cursor.execute("STATEMENT")
我不是很確定,這是否只創建了一次連接,而不管這個類創建的頻率如何。也許有人知道如何只初始化一次連接,以及如何在之后的類中使用它,或者知道我的解決方案是否正確。我很感謝任何幫助!
uj5u.com熱心網友回復:
有點像這樣。 這是一個使用全域的廉價方法。
class Database(object)。
connection = None。
def __init__(self):
if not Database.connection:
Database.connection = mysql.connector.connect(host="127.0.0.1"/span>, user="root"/span>, password="", database="db_test"/span>)
def query(self,sql)。
cursor = Database.connection.cursor()
cursor.execute(sql)
# 在這里做資料庫的事情。
uj5u.com熱心網友回復:
解釋一下
。這里的關鍵詞顯然是類變數。看看官方檔案,我們可以看到,除了實體變數之外,所有的類實體都可以共享類變數,無論存在多少個類實體。
一般來說,實體變數是指每個實體所特有的資料,而類變數是指類的所有實體所共享的屬性和方法:所以讓我們假設你有多個類的實體。該類本身的定義如下。
class Dog: kind = "canine" # class variable shared by all instances. def __init__(self, name): self.name = name # 實體變數對每個實體都是唯一的。為了更好地理解類變數和實體變數之間的區別,我想在這里加入一個小的例子:
d = Dog("Fido"/span>) e = Dog("Buddy") d.kind # shared by all dogs。 "canine"。 e.kind # shared by all dogs。 "canine"。 d.name # only to d "Fido"。 e.name # only to e "Buddy"。解決方案
現在我們知道類的變數是由類的所有實體共享的,我們可以簡單地定義連接和游標,如下圖所示。class Database(object)。 connection = None[/span cursor = Nonedef __init__(self): if Database.connection is None: try: Database.connection = mysql.connector.connect(host="127.0.0.1"/span>, user="root"/span>, password="", database="db_test"/span>) Database.cursor = Database.connection.cursor() except 例外 as error: print("錯誤。連接未建立{}".format(error)) else: print("Connection established"/span>) self.connection = Database.connection self.cursor = Database.cursor結果,與資料庫的連接在一開始就被創建,然后可以被每一個進一步的實體所使用。
uj5u.com熱心網友回復:
你必須做這些的原因是,如果你只是創建一個 么,你就必須做這些事情,因為如果你只是創建了一次連接,然后把它留在那里,那么你就會 將最終試圖使用一個被丟棄的連接
所以你要創建一個連接,并將其留在那里。
因此,你創建一個連接并將其附加到你的應用程式上 然后每當你收到一個新的請求時,檢查該連接是否 是否仍然存在,如果不存在,則重新創建連接并開始運行。
on create_appdef create_app(self)。 if not app.config.get('connection_created') 。 app.database_connection = Database() app.config['connection_created'] = True: app.database_connection = Database()on run app@app.before_request def check_database_connection(self)。 if not app.config.get('connection_created') or not app.database_connection。 app.database_connection = Database() app.config['connection_created'] =True這將確保你的應用程式總是以一個活動的連接運行 并且每個應用程式只創建一次連接
如果連接在任何后續呼叫中被丟棄,那么它將再次被重新創建......。轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/310488.html
標籤:
上一篇:如何在__init__(self)中放置東西:通過在變數中給出引數?
下一篇:Vue中key的作用及原理
