pandas-simple code to obtain data from MySQL and export excel

Demo data:
Insert picture description here

Implementation code:

import pymysql
import pandas as pd
from sqlalchemy import create_engine

# 初始化数据库连接,使用pymysql模块
engine = create_engine("mysql+pymysql://root:root@localhost:3306/python",encoding='utf-8')

# 查询语句,选出testexcel表中的所有数据
sql = """select * from testexcel"""

# read_sql_query的两个参数: sql语句, 数据库连接
df = pd.read_sql_query(sql,con=engine)			# 数据格式为dataframe

# 直接转dataframe
df.to_excel('dsad0.xls',index=False,encoding="utf-8")

Operating results:
Insert picture description hereextension: excel is transferred to the database
reference: pandas reads data from the database and generates a table

Guess you like

Origin blog.csdn.net/weixin_45666249/article/details/114320750