1

我有以下课程:

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我新创建的实例?

4

1 回答 1

3

由于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]))

目前无法测试,如果有问题请见谅:)

于 2012-11-12T03:11:49.690 回答