需要先安装pymysql,ruamel.yaml这个包
pip install pymysql
pip install ruamel.yaml
因为我已经设置好pip源为阿里源,所以下载很丝滑~
新建个mysql.py文件,导入包如下
import pymysql import time import yaml from ruamel import yaml import os import sys path = os.path.dirname(sys.path[0])
正文代码如下:
#写入到txt或者yaml文件中 conn = pymysql.connect(host='192.168.xx.xxx', user = "用户名admin", passwd="正确密码", db="你访问的数据库名", port=3306, charset="utf8") cur = conn.cursor() #我的sql语句,很简单 sql = "select * from notice order by id desc limit 10" cur.execute(sql)
#把结果放在result,有点不妙的感觉,fetch看你心情要导出多少 result = cur.fetchall() # print(type(result)) filename ='DB_Data\'+str(time.strftime("%Y%m%d%H%M%S"))+'.yaml' curpath = os.path.dirname(os.path.realpath(__file__)) yamlpath = os.path.join(curpath, filename) with open(filename,'w',encoding="utf-8") as f: DB_yaml = yaml.dump(result,f,Dumper=yaml.RoundTripDumper,allow_unicode=True) #关闭连接 cur.close() conn.close() print("数据库断开连接!");
解释:Dumper=yaml.RoundTripDumper把yaml格式摆正确;
allow_unicode=True,要unicode码显示utf-8,中文不至于出现乱码