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()