---
title: "python mysql "
author: "mailx8"
date: "2018-01-02T16:48:04Z"
tags: []
categories: ["数据库"]
slug: "python-mysql"
draft: false
lastmod: "2018-01-02T16:48:04Z"
id: 2406408
url: "https://mailx8.iteye.com/blog/2406408"
---

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