【问题标题】:Persist a pandas dataframe to a Postgres SQL table using StringIO使用 StringIO 将 pandas 数据帧持久化到 Postgres SQL 表
【发布时间】:2022-01-20 19:12:48
【问题描述】:

我正在尝试将数据框持久保存到 Postgres 表中,但没有成功。

I have a table table1 with fields f1,f2, f3

df = pd.DataFrame({"f1":["A", "B"],
                   "f2": [1, 2],
                   "f3": ["p", "f"]
            })
buffer = StringIO()
df.to_csv(buffer, sep=",", index=False, header=False)
buffer.seek(0)

# conn is a sqlalchemy.engine.base.Connection object
cur =  conn.connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
# To set the schema
cur.execute(f"SET search_path TO my_schema")
cur.copy_from(buffer,'table1', sep=",")
cur.close()

没有抛出错误,但是数据没有写入db表。

【问题讨论】:

    标签: python pandas postgresql sqlalchemy stringio


    【解决方案1】:

    尝试在cur.close() 之后调用conn.connection.commit()

    cur.execute(f"SET search_path TO my_schema")
    cur.copy_from(buffer,'table1', sep=",")
    cur.close()
    
    # Add this line
    conn.connection.commit()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      • 2021-03-07
      • 1970-01-01
      • 2016-12-03
      相关资源
      最近更新 更多