简体   繁体   English

使用 StringIO 将 pandas dataframe 保存到 postgres sql 表

[英]Persist a pandas dataframe to a postgres sql table using StringIO

I am trying to persist a dataframe into a postgres table with no luck.我正在尝试将 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()

No error is thrown, but data is not written to the db table.不会抛出错误,但数据不会写入 db 表。 Wit's end.束手无策。

Try calling conn.connection.commit() after cur.close() :尝试在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM