Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def insert_data_psql(data: pd.DataFrame, schema: str, table: str):
- # Creating buffer for csv file
- buffer = StringIO()
- # Converting DataFrame to CSV
- data.to_csv(buffer, header=False, index=False)
- buffer.seek(0)
- # Creating connection with PostgreSQL DB
- conn = psycopg2.connect(host=HOST,
- port=PORT,
- user=USER,
- password=PASSWORD,
- database=DATABASE,
- options=f"-c search_path={schema}")
- # Connecting to data base
- cursor = conn.cursor()
- # Truncate table
- cursor.execute(f'TRUNCATE TABLE "{schema}"."{table}"')
- # Insert data to table
- cursor.copy_from(buffer, table, sep=",", null='')
- conn.commit()
- # Closing connection
- conn.close()
Advertisement
Add Comment
Please, Sign In to add comment