当前位置 : 主页 > 编程语言 > python >

python之excel与mysql之间的交互

来源:互联网 收集:自由互联 发布时间:2022-06-15
一.准备工作 1.1安装以下包 pip install openpyxl pip install sqlalchemy pip install pandas 1.2配置数据库的东西在conf.py文件下 DATABASE_CONFIG = { "HOST": "127.0.0.1", "USERNAME": "root", "PASSWORD": "", "DATABASE": "bike

一.准备工作

1.1安装以下包

pip install openpyxl
pip install sqlalchemy
pip install pandas

 

1.2配置数据库的东西在conf.py文件下

python之excel与mysql之间的交互_mysqlpython之excel与mysql之间的交互_mysql_02

DATABASE_CONFIG = {
"HOST": "127.0.0.1",
"USERNAME": "root",
"PASSWORD": "",
"DATABASE": "bike_ods",
"PORT": 3306,
}

View Code

1.3 mysql --->  excel

python之excel与mysql之间的交互_mysqlpython之excel与mysql之间的交互_mysql_02

from sqlalchemy import create_engine
import pandas as pd

from conf import DATABASE_CONFIG

# 创建数据库连接
ip = DATABASE_CONFIG["HOST"]
username = DATABASE_CONFIG["USERNAME"]
password = DATABASE_CONFIG["PASSWORD"]
ods = DATABASE_CONFIG["DATABASE"]
# 文件输出
excel_file = "out.xlsx"
engine = create_engine(f'mysql+pymysql://{username}:{password}@{ip}/{ods}')
# 读取mysql数据
select_sql = f"select * from areafence"
db = pd.read_sql(select_sql, con=engine)
# 导出数据到excel
db.to_excel(excel_file)

View Code

1.4 excel ---------> mysql

python之excel与mysql之间的交互_mysqlpython之excel与mysql之间的交互_mysql_02

from sqlalchemy import create_engine
import pandas as pd

from conf import LOCALHOST_CONFIG as DATABASE_CONFIG

# 创建数据库连接
ip = DATABASE_CONFIG["HOST"]
username = DATABASE_CONFIG["USERNAME"]
password = DATABASE_CONFIG["PASSWORD"]
ods = DATABASE_CONFIG["DATABASE"]
# 文件输出
excel_file = "out.xlsx"


# 创建数据库连接
engine = create_engine(f'mysql+pymysql://{username}:{password}@{ip}/{ods}')
# 读取xlsx文件
df = pd.read_excel(excel_file)
# 导入到mysql数据库
df.to_sql(name='test_data', con=engine, index=False, if_exists='replace')

View Code

 1.5 如果默认端口不是3306

engine = create_engine('mysql://user:password@localhost:3306/test?charset=utf8mb4')

 

-----------------------------------------------------------------------------------------------------------------------------------------

【文章转自防cc http://www.558idc.com/gfcdn.html 复制请保留原URL】
上一篇:pymysql模块,python与MySQL之间的交互
下一篇:没有了
网友评论