import pymysql import csv import codecs def get_conn(): db = pymysql.connect(host="12xxx",port=3306, user="root",password="1", db="pydata201806",charset="utf-8") return db def execute_all(cursor,sql,args): cursor.execute(sql,args) return cursor.fetchall() def red_mysql_to_csv(filename): with codecs.open(filename=filename,mode='w',encoding='utf-8')as f: write = csv.writer(f,dialect='excel') write.writerow(['data','ss','yy','gg','ff','xx','ss','cc','da']) db = get_conn() cursor =db.cursor() sql ='select * from tb_csv' results = execute_all(cursor=cursor,sql=sql,args=None) for res in results: print(res) write.writerow(res) if __name__ == '__main__': red_mysql_to_csv(r"E:\results4.csv")