一种是导入sqlalchemy包,另一种是导入psycopg2包。
具体用法如下(此处以postgre数据库举例)
第一种:
# 导入包
from sqlalchemy import create_engine
import pandas as pd
from string import Template
engine = create_engine("oracle://user:pwd@***:***/racdb", echo=False)
# 初始化引擎
engine = create_engine('postgresql+psycopg2://' + pg_username + ':' + pg_password + '@' + pg_host + ':' + str(
pg_port) + '/' + pg_database)
query_sql = """
select * from $arg1
"""
query_sql = Template(query_sql) # template方法
df = pd.read_sql_query(query_sql .substitute(arg1=tablename),engine) # 配合pandas的方法读取数据库值
# 配合pandas的to_sql方法使用十分方便(dataframe对象直接入库)
df.to_sql(table, engine, if_exists='replace', in