Python将dataframe格式的大批量数据快速存入postgresql数据库中
python🔗一切
基于Python实现大批量dataframe格式数据快速存入postgresql中
之前写过一篇to_sql函数存入postgresql库的,当时数据量比较小,感觉速度还行,最近从es拉取的数据太多了,慢到怀疑人生。通过查资料和同事交流,发现了copy_from函数,天呐,这个效率也太快了吧!!
# 加载必要的python库
import psycopg2
from io import StringIO
from sqlalchemy import create_engine
import pandas as pd
# 输出表名
output_tablename = ''
engine = create_engine('postgres://username:password@ip:port/database') # username为用户名、password为密码、ip为IP地址、database为数据库名称
pd_engine = pd.io.sql.pandasSQL_builder(engine)
table = pd.io.sql.SQLTable(output_tablename, pd_engine, frame = df, index= False, if_exists='fail', schema='path_test') # frame表示需要写入mpp库中的dataframe格式的数据
table.create()
io_buff = StringIO()
df.to_csv(io_buff, sep='\t', index=False, time.time())
io_buff_value = io_buff.getvalue()
coon = psycopg2.connect(host='', user='', password='', database='', port='')
cur = coon.cursor()
cur.copy_from(StringIO(io_buff_value), 'path_test.'+output_tablename) #path_test表示实际的schema
coon.commit()
cur.close()
coon.close()
print('写入成功')