from sqlalchemy import create_engine create_engine(*args, **kwargs) # 标准格式是: # create_engine(dialect[+driver]://user:password@host/dbname[?key=value..])举例:
数据库类型是mysql,使用pymysql库
from sqlalchemy import create_engine
engine=create_engine('mysql+pymysql://root:root@localhost:3306/databasename')
完成以上对象创建后,使用pandas对sql数据库进行读写操作。
读取
直接从数据库中读取数据,首先定义sql语句,然后运行并打印结果
import pandas as pd sql_command='select * from table_name' print(pd.read_sql(sql_command,engine))写入
首先读取需要写入的数据,此处以excel文件为例
import pandas as pd df=pd.read_excel(path)
然后向数据库写入数据,这里使用to_sql方法
from sqlalchemy import create_engine
engine=create_engine('mysql+pymysql://root:root@localhost:3306/databasename')
df.to_sql('table_name',engine,index=false,if_exists='false')
可见相较于pymysql进行mysql的读写来说,使用sqlalchemy代码更加简洁,先写这么多吧。


