为了获取SELECT语句,这是我通常要做的事情:
stmt_select = "SELECT * FROM {0} ORDER BY id".format(tbl)
cursor.execute(stmt_select)
for row in cursor.fetchall():
output.append("%3s | %10s | %19s | %8s |" % (
row[0],
row[1],
row[2],
row[3],
))这种方法的问题是,我需要指定索引列,而不是列名。如何通过指定列名而不是总是指定索引来访问?最好不指定我想要在for循环中获取的列名。
发布于 2019-01-27 14:16:33
这是namedtuples的一个非常常见的用法,你可以创建一个命名的元组--它允许访问属性。
与问题中的代码相关的示例:
from collections import namedtuple
DBEntity = namedtuple("DBEntity", ("first_cell","second_cell","third_cell", "fourth_cell"))
stmt_select = "SELECT * FROM {0} ORDER BY id".format(tbl)
cursor.execute(stmt_select)
for row in cursor.fetchall():
t_row = DBEntity(*row)
output.append("%3s | %10s | %19s | %8s |" % (
t_row.first_cell,
t_row.seconnd_cell,
t_row.third_cell,
t_row.fourth_cell,
))此外(尽管根据您的程序的用途,可能有点夸大其词)-您也可以使用sqlalchemy进行ORM
https://stackoverflow.com/questions/54385282
复制相似问题