【pandas】pandas 写入postgresql 比较快的方法

一种是导入sqlalchemy包,另一种是导入psycopg2包。
具体用法如下(此处以postgre数据库举例)
postgresql://用户名:密码@host:port/db_name

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)

 

#一种是导入sqlalchemy包,另一种是导入psycopg2包。
#具体用法如下(此处以postgre数据库举例)
#postgresql://用户名:密码@host:port/db_name

#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)


def write_to_table(df, table_name, schema_name, if_exists='fail'):
    import io
    import pandas as pd
    from sqlalchemy import create_engine
    db_engine = create_engine('postgresql://***:***@***:***/***')# 初始化引擎
    string_data_io = io.StringIO()
    df.to_csv(string_data_io, sep='|', index=False)
    pd_sql_engine = pd.io.sql.pandasSQL_builder(db_engine)
    table = pd.io.sql.SQLTable(table_name, pd_sql_engine, frame=df,
                               index=False, if_exists=if_exists,schema = schema_name)
    table.create()
    string_data_io.seek(0)
    string_data_io.readline()  # remove header
    with db_engine.connect() as connection:
        with connection.connection.cursor() as cursor:
            copy_cmd = "COPY {}.{} FROM STDIN HEADER DELIMITER '|' CSV".format(table_name, schema_name)
            cursor.copy_expert(copy_cmd, string_data_io)
        connection.connection.commit()

 

至此完成!!!

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值