栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何将Pandas DataFrame升级到PostgreSQL表?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何将Pandas DataFrame升级到PostgreSQL表?

如果您使用的是PostgreSQL 9.5或更高版本,则可以使用临时表和一条

INSERT ... ON CONFLICT
语句执行UPSERT :

with engine.begin() as conn:    # step 0.0 - create test environment    conn.execute(sa.text("DROp TABLE IF EXISTS main_table"))    conn.execute(        sa.text( "CREATE TABLE main_table (id int primary key, txt varchar(50))"        )    )    conn.execute(        sa.text( "INSERT INTO main_table (id, txt) VALUES (1, 'row 1 old text')"        )    )    # step 0.1 - create Dataframe to UPSERT    df = pd.Dataframe(        [(2, "new row 2 text"), (1, "row 1 new text")], columns=["id", "txt"]    )    # step 1 - create temporary table and upload Dataframe    conn.execute(        sa.text( "CREATE TEMPORARY TABLE temp_table (id int primary key, txt varchar(50))"        )    )    df.to_sql("temp_table", conn, index=False, if_exists="append")    # step 2 - merge temp_table into main_table    conn.execute(        sa.text(""" INSERT INTO main_table (id, txt)  SELECT id, txt FROM temp_table ON ConFLICT (id) DO     UPDATe SET txt = EXCLUDED.txt """        )    )    # step 3 - confirm results    result = conn.execute(sa.text("SELECT * FROM main_table ORDER BY id")).fetchall()    print(result)  # [(1, 'row 1 new text'), (2, 'new row 2 text')]


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/626549.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号