Search
 
SCRIPT & CODE EXAMPLE
 

SQL

write pandas dataframe to postgresql table psycopg2

# Write pandas df into postgres table
import psycopg2
import numpy as np
import psycopg2.extras as extras
import pandas as pd
  
def execute_values(conn, df, table):  
    tuples = [tuple(x) for x in df.to_numpy()]  
    cols = ','.join(list(df.columns))
    # SQL query to execute
    query = "INSERT INTO %s(%s) VALUES %%s" % (table, cols)
    cursor = conn.cursor()
    try:
        extras.execute_values(cursor, query, tuples)
        conn.commit()
    except (Exception, psycopg2.DatabaseError) as error:
        print("Error: %s" % error)
        conn.rollback()
        cursor.close()
        return 1
    print("the dataframe is inserted")
    cursor.close()  
  
conn = psycopg2.connect(
    database="ENVIRONMENT_DATABASE", user='postgres', password='pass', host='127.0.0.1', port='5432'
)
 
df = pd.read_csv('fossilfuels.csv')  
execute_values(conn, df, 'fossil_fuels_c02')
Comment

PREVIOUS NEXT
Code Example
Sql :: default constraint in ms sql 
Sql :: referential integrity constraint 
Sql :: mysql isnull 
Sql :: write sql query to find the second highest salary of employee 
Sql :: xampp import sql file command line 
Sql :: oracle revoke grant 
Sql :: mysql record group by created date count 
Sql :: update with select postgresql 
Sql :: jwt laravel 
Sql :: add column postgres with default value 
Sql :: mysql update from select on same table 
Sql :: how to extract only year and month from date in sql 
Sql :: What is dialect for Postgres 
Sql :: How to check if the column exists in sql table 
Sql :: drop all tables in azure sql database 
Sql :: sql date format dd-mm-yyyy 
Sql :: constraints to columns SQL 
Sql :: oracle drop sequence if exists 
Sql :: sql if clause within where clause 
Sql :: import sql in postgresql 
Sql :: Get first name and last name from full name string in SQL 
Sql :: oracle table free space 
Sql :: sql value exists in column 
Sql :: sql set 
Sql :: mysql select distinct date from timestamp 
Sql :: sql server drop column 
Sql :: average salary in sql 
Sql :: mysql url data type 
Sql :: sql get duplicates by composite 
Sql :: limit offset sql server 
ADD CONTENT
Topic
Content
Source link
Name
8+7 =