游标执行后返回的结果都只是数据,但是不带有列名标识。这里需要处理2个问题:
解决上面的2个问题,在python里面可以采用下面的2种方式来处理。
下面是示例代码:
Result_From_DB# MySQL 数据库 import mysql from mysql import connector from collections import namedtuple def generate_namedtuple(cur): from collections import namedtuple fieldnames = [d[0].lower() for d in cur.description] Record = namedtuple('Record', fieldnames) rows = cur.fetchall() if not rows:return else: return map(Record._make, rows) def generate_dicts(cur): fieldnames = [d[0].lower() for d in cur.description] while True: rows = cur.fetchmany() if not rows: return for row in rows: yield dict(zip(fieldnames, row)) if __name__ == '__main__': user = 'herbert' pwd = '851020' host = '127.0.0.1' db = 'world' cnx = mysql.connector.connect(user=user, password=pwd, host=host,database=db) cur = cnx.cursor() cur.execute("SELECT Name, CountryCode, District, Population FROM CITY\ where CountryCode = 'CHN' AND Population > 500000") for r in generate_dicts(cur): print(r['name'], r['population']) cur.execute("SELECT Name, CountryCode, District, Population FROM CITY\ where CountryCode = 'CHN' AND Population > 500000") print("-----------------------------") for k in generate_namedtuple(cur): print(k.name, k.population) cur.close() cnx.close()
需要注意几点: