python 连接mysql 数据库

第一步 下载pymysql 包

python 连接mysql 数据库

python 连接mysql 数据库

第二步:编写mysql.py 连接mysql 查询数据遍历

import pymysql
db = pymysql.connect(host='localhost',
                           user='root',
                           password='123456',
                           db='crow',
                           port=3306,
                           charset='utf8')
try:
    #获取一个游标
   with db.cursor() as cursor:
       sql='select * from city'
       cout=cursor.execute(sql)
       print("数量: "+str(cout))

       for row in cursor.fetchall():
            #注意int类型需要使用str函数转义
           print("ID: "+str(row[0])+'  名字: '+str(row[1])+"  性别: "+str(row[2]))
       db.commit()

finally:
    db.close()