1.安装pymysql,pandas
pip install pymysql
pip install pandas
2.用pandas强大的连接数据导出数据功能巨简单:
import pandas as pd
import pymysql
mysql_cn = pymysql.connect(host='(服务器地址)', port=(端口号), user='(用户名)', passwd='(密码)', db='(数据库名)', charset = "(编码格式)")
df = pd.read_sql('select * from (表名);', con=mysql_cn)
print(df)
df.to_excel("./F10.xlsx", sheet_name="F10")
要求:只导出文件,每个数据用“”(双引号)隔开,并且把数据库内的回车删除,数据之间是逗号类似这个:
“aa”,“18,“bbb””
贴上代码:
import pandas as pd
import pymysql
mysql_cn = pymysql.connect(host='(ip地址)', port=(端口), user='(用户名)', passwd='(密码)', db='(数据库名)', charset = "(编码格式)")
df = pd.read_sql('select * from TCommodityF10;', con=mysql_cn)
df = df.replace("\n", "", regex=True)
print(df)
df.to_csv("./F10", quoting=1)