【问题标题】:How to create a temporary table by passing in data to psycopg2?如何通过将数据传递给 psycopg2 来创建临时表?
【发布时间】:2022-06-18 23:50:28
【问题描述】:

我有一个 pandas 数据框,我想将它作为临时表传递给 psycopg2 execute 语句。这应该很简单:

伪代码...

string = """
  with temporary_table (id, value) as (values %s)

  select * from temporary_table
"""
cur.execute(string, df)

其中df 只是一个带有idvalue 列的数据框。

使用什么语法可以将这些数据作为临时表传入并在查询中使用?

【问题讨论】:

  • A df 是 Panda 对象,不能直接用作 execute 中的值源。您将需要使用to_sql。可能是两部分脚本:1)创建临时表 2)使用to_sql 在同一会话中填充它。否则,您将需要从df 中提取数据,例如dict 并使用它。
  • @AdrianKlaver 是的,对不起,我看到了混乱,但我知道将 pandas 数据帧传递给 sql 没有意义......我目前正在做的方式是将数据帧转换为元组的元组,将其转换为字符串,然后使用字符串剪辑删除第一个和最后一个(),并将字符串作为变量传递给%s,我只是想知道如果有更优雅的方法,如果有,请扩展您的答案。

标签: psycopg2


【解决方案1】:

我会使用 df.to_sql 在 Postgres 数据库中创建一个临时表,或者使用值执行插入 sql 查询,查询它并在进程结束时删除它

【讨论】:

    【解决方案2】:

    我认为符合您要求的测试用例:

    import psycopg2
    from psycopg2.extras import execute_values
    
    con = psycopg2.connect("dbname=test user=postgres host=localhost port=5432")
    
    sql_str = """WITH temporary_table (
        id,
        value
    ) AS (
        VALUES %s
    )
    SELECT
        *
    FROM
        temporary_table
    """
    cur = con.cursor()
    execute_values(cur, sql_str, ((1, 2), (2,3)))
    cur.fetchall()                                                                                                                                                                                                          
    [(1, 2), (2, 3)]
    

    使用来自Fast Execution Helpersexecute_values

    更新

    坚持execute:

    import psycopg2
    from psycopg2 import sql
    
    con = psycopg2.connect("dbname=test user=postgres host=localhost port=5432")
    cur = con.cursor()
    
    input_data = ((1,2), (3,4), (5,6))
    
    sql_str = sql.SQL("""WITH temporary_table (
        id,
        value
    ) AS (
        VALUES {}
    )
    SELECT
        *
    FROM
        temporary_table
    """).format(sql.SQL(', ').join(sql.Placeholder() * len(input_data)))
    
    cur.execute(sql_str, input_data)
    
    cur.fetchall()                                                                                                                                                            
    [(1, 2), (3, 4), (5, 6)]
    

    【讨论】:

    • 你能做同样的事情,只是没有execute_values吗?由于不值得解释的原因,我无法使用该功能。
    • 你可以使用什么,例如execute_batchexecute_many?
    • 我的问题只是关于使用cur.execute
    • 查看使用execute更新
    猜你喜欢
    • 2023-02-24
    • 1970-01-01
    • 2014-06-11
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多