[英]Persist a pandas dataframe to a postgres sql table using StringIO
我正在嘗試將 dataframe 持久保存到 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 表。 束手無策。
嘗試在 cur.close conn.connection.commit()
cur.close()
:
cur.execute(f"SET search_path TO my_schema")
cur.copy_from(buffer,'table1', sep=",")
cur.close()
# Add this line
conn.connection.commit()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.