Python Pandas connects to the Mysql database and adds row records and query records to the table

mainly uses the two libraries SQLAlchemy and PyMySQL integrated in Python to add new row records to the database. SQLAlchemyProvides Python with a unified interface for different databases, which can be used to connect to most common databases, such as Postges, MySQL, SQLite, Oracle, etc. PyMySQL is a library used in Python3.x version to connect to the MySQL server.
1. Add new records to the table

import pandas as pd
from sqlalchemy import create_engine
import pymysql
engine=create_engine(r"mysql+pymysql://root:[email protected]:3301/database_name")#root:[email protected]:3301/database_name   用户名:密码@ip地址:端口号/表名称
data_sale.to_sql('table_name_1',engine,if_exists='append',index= False)#向table_name_1表中新增data_sale记录,非覆盖新增
data_order.to_sql('table_name_2',engine,if_exists='append',index= False)#向table_name_2表中新增data_order记录,非覆盖新增

2. Execute the query statement

sql='''
select * from table_name_1
'''
df = pd.read_sql_query(sql, engine)#执行查询语句并将查询结果赋值给df

Guess you like

Origin blog.csdn.net/p1306252/article/details/122623840