gpt4 book ai didi

python - 在 Python 类中的何处建立数据库连接以运行多个查询?

转载 作者:搜寻专家 更新时间:2023-10-30 23:37:06 25 4
gpt4 key购买 nike

我正在编写一个涉及多个 INSERT 语句的类,这些语句分为不同的函数。举例来说,我正在为 employeeStart 编写一个类,当一名员工开始工作时,我会得到一个员工姓名,并将该值插入到 grain staff_id | 的表 'staff' 中。员工姓名staff_id 是一个 auto_increment 字段,因此它会使用新值填充自身。

然后我获取该 staff_id 值并将其插入表“badge”中,该表具有 badge_number | staff_id 其中 bade_number 也是自增。

所以类看起来像:

class employeeStart:
staff_id = None
badge_number = None

def __init__(self, staff_name):
self.staff_id = setStaffId(staff_name)
self.badge_number = setBadgeNumber(staff_id)

这都是在Mysql数据库上,所以我只建立了一次数据库连接,对吧?如果是这样,那应该在哪里发生?是在 __init__ 函数之前,在 __init__ 函数内部,还是在将运行的第一个函数 - setStaffId 中?

最佳答案

您可以使用 MySQLdb 的上下文管理器语法处理连接和错误处理,将查询包装在 with 语句中。

import MySQLdb

class employeeStart:

def set_staff_id(self, connection):
with connection as cursor:
cursor.execute("INSERT INTO staff (name) VALUES (%s)", staff_name)
return cursor.lastrowid

def set_badge_id(self, connection):
with connection as cursor:
cursor.execute("INSERT INTO badge (staffid) VALUES (%s)", staff_id)
return cursor.lastrowid

def __init__(self):
connection = MySQLdb.connect(...)
self.staff_id = self.set_staf_id(connection)
self.badge_id = self.set_badge_id(connection)

但我真的不认为这里需要上课...

关于python - 在 Python 类中的何处建立数据库连接以运行多个查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40731563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com