2

I am trying to persist a dataframe into a Postgres table with no luck.

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
SeriousGal
  • 21
  • 2

1 Answers1

1

Try calling conn.connection.commit() after 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()