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

如何将pandas DataFrame升级到Microsoft SQL Server表?

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

如何将pandas DataFrame升级到Microsoft SQL Server表?

有两种选择:

  1. 使用
    MERGE
    语句代替
    INSERT ... ON CONFLICT
  2. 使用
    UPDATe
    带a的语句
    JOIN
    ,后跟条件语句
    INSERT

MERGE的T-SQL文档说:

性能提示:当两个表具有匹配特征的复杂混合时,为MERGE语句描述的条件行为最有效。例如,如果不存在则插入行,或者如果匹配则更新行。当仅基于另一个表的行更新一个表时,可使用基本的INSERT,UPDATE和DELETE语句提高性能和可伸缩性。

在许多情况下,仅使用分隔符

UPDATE
INSERT
语句会更快,更简单。

engine = sa.create_engine(    connection_uri, fast_executemany=True, isolation_level="SERIALIZABLE")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 - upload Dataframe to temporary table    df.to_sql("#temp_table", conn, index=False, if_exists="replace")    # step 2 - merge temp_table into main_table    conn.execute(        sa.text(""" UPDATE main SET main.txt = temp.txt FROM main_table main INNER JOIN #temp_table temp     ON main.id = temp.id """        )    )    conn.execute(        sa.text(""" INSERT INTO main_table (id, txt)  SELECt id, txt FROM #temp_table WHERe id NOT IN (SELECt id FROM main_table)  """        )    )    # 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/624329.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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