python">def iquery(conn, sql, rowfactory=tuple, batch=1, *args, **kwgs):
"""在给定的数据库连接conn上执行sql(可带有参数*args或命名参数**kwgs)
rowfactory指定输出物为元组/字典(或字典的扩展类)
/或使用用命名参数的函数的结果
batch <= 0时, 直接全部输出
batch == 1时, 逐记录输出
batch >= 1时, 按指定的数量形成批次列表
"""
from itertools import imap
from contextlib import closing
with closing(conn.cursor()) as curr:
if curr.execute(sql, args or kwgs):
if rowfactory == tuple:
factory = tuple
elif issubclass(rowfactory, dict):
fields = [f[0].lower() for f in curr.description]
factory = lambda x: rowfactory(zip(fields, x))
else:
fields = [f[0].lower() for f in curr.description]
factory = lambda x: rowfactory(**dict(zip(fields, x)))
if batch <= 0:
yield imap(factory, curr.fetchall())
elif batch == 1:
for row in imap(factory, curr):
yield row
else:
rows = curr.fetchmany(batch)
while rows:
yield map(factory, rows)
rows = curr.fetchmany(batch)
标签:python