Search
 
SCRIPT & CODE EXAMPLE
 

SQL

python pandas df to postgres json table

# 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 :: alter table add multiple columns postgresql 
Sql :: unsigned int in mysql 
Sql :: change mysql version to 5.7 in ubuntu 
Sql :: mysql select into new table 
Sql :: select milliseconds mysql 
Sql :: oracle revoke 
Sql :: 1) PostgreSQL DESCRIBE TABLE using psql 
Sql :: sql table 
Sql :: laravel jwt 
Sql :: mariadb hours between two dates 
Sql :: add bool column in sql 
Sql :: check if value is equal to something sql 
Sql :: sql datetime format dd/mm/yyyy hh:mm am/pm 
Sql :: mysql 1 hour ago 
Sql :: how to delete the rows with null values in mysql 
Sql :: sql select first and last record of each group 
Sql :: adding constraints to columns SQL 
Sql :: SQL ORDER BY ASC (Ascending Order) 
Sql :: mysql group by date 
Sql :: creating index in mysql 
Sql :: join multiple tables sql 
Sql :: date in oracle 
Sql :: postgres user permissions 
Sql :: mysql date equals to current_date plus days 
Sql :: row to json in sql server 
Sql :: T-SQL - Delete Column 
Sql :: how to find average in sql 
Sql :: change column data type sql 
Sql :: mysql not defined 
Sql :: how insert auto increment 
ADD CONTENT
Topic
Content
Source link
Name
3+6 =