Pandas读写MySQL数据库

我们需要以下三个库来实现Pandas读写MySQL数据库:

pandas、sqlalchemy、pymysql

其中,

pandas模块提供了read_sql_query()函数实现了对数据库的查询,to_sql()函数实现了对数据库的写入。并不需要实现新建MySQL数据表。

sqlalchemy模块实现了与不同数据库的连接,

pymysql模块则使得Python能够操作MySQL数据库。

一、读取数据库

示例:

#DBAPI2 connection方式连接
import mysql.connector
import pandas as pd

conn=mysql.connector.connect(host='127.0.0.1',user='root', passwd='password', db='test')
sql='select * from mytable'
df=pd.read_sql(sql,conn)

示例:

#SQLAlchemy engine方式
from sqlalchemy import create_engine
import pandas as pd
engine = create_engine('mysql+mysqlconnector://root:[email protected]:3306/test')
df=pd.read_sql(sql,engine )


价格: 1.00 元
VIP会员价格:1.00元终身会员免费
温馨提示:登录付款后可永久阅读隐藏内容。 付费可读