从SQL查询创建类的实例

时间:2012-11-12 02:26:32

标签: python sqlite instantiation

我有以下课程:

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条目传递给我新创建的实例?

1 个答案:

答案 0 :(得分: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]))

现在无法测试,所以如果它离开了道歉:)