为了获取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循环中获取的列名。
答案 0 :(得分:1)
这是namedtuples的非常普遍的用法,您可以创建一个namedtuple-它允许访问属性。
与问题代码相关的示例:
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