我有一个递归 python 函数,它处理数据并需要从函数内部将数据写入 mysql 数据库。
我通常像这样连接到 mysql 数据库
def MyFunc(x, y):
conn = mysql.connector.connect(
user = "myuser",
password = "SuperSecretPassword",
host = "127.0.0.1",
database = "MyDatabase")
# Process some data here, then write it to the DB
cursor = conn.cursor()
cursor.execute("INSERT INTO table a, b, c VALUES(1,2,3)")
conn.commit()
MyFunc(x, y)
虽然这可行,但如果我在我的函数中这样做,我将创建数百个(如果不是数千个)到我的 mysql 数据库的连接,具体取决于递归在我正在处理的数据中的深度。这似乎是一个非常糟糕的主意。
我尝试在代码的主要部分(在函数之外)创建连接和游标,然后像全局变量一样从函数内部引用它们:
global cursor.execute("INSERT INTO table a, b, c VALUES(1,2,3)")
global conn.commit()
但这没有用。
是否可以在像这样的递归函数中写入 python 中的数据库,并且只打开与数据库的 1 个连接?
最佳答案
为什么不在 Python 模块中保留一个连接,例如:
# script.py
conn = mysql.connector.connect(
user = "myuser",
password = "SuperSecretPassword",
host = "127.0.0.1",
database = "MyDatabase")
def MyFunc(x, y):
# Process some data here, then write it to the DB
cursor = conn.cursor()
cursor.execute("INSERT INTO table a, b, c VALUES(1,2,3)")
conn.commit()
MyFunc(x, y)
关于python - 递归函数中数据库连接的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34829923/