开发者

Python Object from a SQL row (with a large number of columns)

Given the following SQL query,

    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()

I would like to pass the row object as an argument in creating a new object, e.g.

A = CertainTypeOfApple(row)

In the __init__(self,row) of class CertainTypeOfApple, I would like to transform each of the fields, i.e. field1, field2,..., to object attributes. Is there some str开发者_开发技巧aighforward way to do that? In other words, I would like to do this in a more compact way:

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


If your fields are known as a list of string you should use setattr builtin function to set the field from its name.

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)

And your init would look like:

def __init__(self, row, fields):
    for field in fields:
        setattr(self, field, getattr(row, field))

In one of my programs I have classes representing each table and we use this method to load data from the database (we do it with sqlite but you should be able to do it with SQL server). However the class reprensenting the table owns the list of fields, making things cleaner (see our class in pynmj)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜