【发布时间】:2018-10-15 19:19:42
【问题描述】:
在 Python 中,我将 sqlite3 中的行读取到一个简单数据结构的对象中。在分配的那一刻,我必须将行分配给一系列变量。有没有办法以更简单的方式做到这一点?
我在下面包含了一些示例代码,希望能说明我的问题。
import sqlite3
class studentDef(object):
def __init__(self):
self.firstName = 'x'
self.lastName = 'x'
self.id = 'x'
self.address1 = 'x'
self.address2 = 'x'
self.city = 'x'
self.state = 'x'
self.zip = 'x'
self.status = 0
def main():
mystudent = studentDef()
db = sqlite3.connect('students.sqlite3')
cursor = db.cursor()
selectTxt = "select * from students where status = 1"
cursor.execute(selectTxt)
rows = cursor.fetchall()
for index in range(0,len(rows)):
mystudent.firstName, mystudent.lastName, mystudent.id, mystudent.address1, \
mystudent.address2, mystudent.city, mystudent.state, mystudent.zip, \
mystudent.status = row[index]
processStudent(mystudent)
if __name__ == '__main__':
main()
我当前的代码正在阅读 50 多列,并且赋值语句变得有点毛茸茸!由于我仍在开发中,所以在添加、删除或修改列时,我经常弄乱赋值语句。
有没有更简单的方法来做类似的事情:
mystudent = row[index]
我的另一个问题是我在大约 5 个其他程序中这样做。所以每次我更改数据库布局时,我都会花费大量时间来更新我的所有代码。
【问题讨论】: