Guest User

Untitled

a guest
Aug 12th, 2022
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.85 KB | None | 0 0
  1. def insert_data_psql(data: pd.DataFrame, schema: str, table: str):
  2.     # Creating buffer for csv file
  3.     buffer = StringIO()
  4.    
  5.     # Converting DataFrame to CSV
  6.     data.to_csv(buffer, header=False, index=False)
  7.     buffer.seek(0)
  8.    
  9.     # Creating connection with PostgreSQL DB
  10.     conn = psycopg2.connect(host=HOST,
  11.                         port=PORT,
  12.                         user=USER,
  13.                         password=PASSWORD,
  14.                         database=DATABASE,
  15.                         options=f"-c search_path={schema}")
  16.                        
  17.     # Connecting to data base
  18.     cursor = conn.cursor()
  19.     # Truncate table
  20.     cursor.execute(f'TRUNCATE TABLE "{schema}"."{table}"')
  21.     # Insert data to table
  22.     cursor.copy_from(buffer, table, sep=",", null='')
  23.     conn.commit()
  24.     # Closing connection
  25.     conn.close()
Advertisement
Add Comment
Please, Sign In to add comment