python 连接mysql 数据库

来源:互联网 发布:电脑有网络玩不了游戏 编辑:程序博客网 时间:2024/05/22 15:55

第一步 下载pymysql 包



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

import pymysqldb = 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()

原创粉丝点击