gpt4 book ai didi

python - 从 SQL 查询创建类的实例

转载 作者:行者123 更新时间:2023-11-30 23:39:44 26 4
gpt4 key购买 nike

我有以下类(class):

class SomeClass:
def __init__(self, name, date):
self.name = name
self.date = date

现在我在另一个模块中有一个函数,它连接到 SQLite 数据库并执行查询:

def getEntry(user):
data = []
connection = lite.connect(database)
with connection:
cur = connection.cursor()
cur.execute("SELECT name, date FROM table WHERE column = ?", [user])
events = cur.fetchall()
# instantiate an instance of `SomeClass`
return data

那么我如何创建 SomeClass 实例并将 namedate 条目传递给我新创建的实例?

最佳答案

由于 fetchall() 返回行列表,因此您应该能够执行此操作(这也应该涵盖返回多个结果的情况):

for result in events:
my_instance = SomeClass(result[0], result[1])
# Do whatever you want to do with the instances, which looks like
# it may be appending to data
data.append(my_instance) # Or data.append(SomeClass(result[0], result[1]))

现在无法测试,如果还差得远的话,我们深表歉意:)

关于python - 从 SQL 查询创建类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13337629/

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