SQL行中的Python对象(具有大量列)

SQL行中的Python对象(具有大量列),python,Python,给定以下SQL查询 cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass') cursor = cnxn.cursor() cursor.execute("select field1, field2, field3, fieldA, fieldB, fieldB from users") row = cursor.fetchone() 我希望

给定以下SQL查询

    cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass')
    cursor = cnxn.cursor()
cursor.execute("select field1, field2, field3, fieldA, fieldB, fieldB from users")
    row = cursor.fetchone()
我希望在创建新对象时将row对象作为参数传递,例如

A = CertainTypeOfApple(row)
在CertainTypeOfApple类的
\uuuuu init\uuuu(self,row)
中,我想将每个字段,即field1、field2、…,转换为对象属性。有没有什么好办法?换言之,我想以一种更紧凑的方式:

self.field1 = row.field1
self.field2 = row.field2
...

如果字段被称为字符串列表,则应使用内置函数从字段名称设置字段

fields = ["field1", "field2", "field3", "fieldA", "fieldB"]
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass')
cursor = cnxn.cursor()
cursor.execute("select %s from users" % fields)
row = cursor.fetchone()
CertainTypeTypeOfApple(row, fields)
您的init将如下所示:

def __init__(self, row, fields):
    for field in fields:
        setattr(self, field, getattr(row, field))
在我的一个程序中,我有代表每个表的类,我们使用此方法从数据库加载数据(我们使用sqlite进行加载,但您应该能够使用SQL server进行加载)。但是,表示表的类拥有字段列表,这使事情变得更清晰(请参阅)