import pandas as pd
import psycopg2 as psy


data = pd.read_csv(r'co2_emission.csv')
df = pd.DataFrame(data)
df2 = df.drop_duplicates()
co = None


try : 
    co = psy.connect(host='berlin',
        database = 'dbmalanone',
        user = 'malanone',
        password = 'azertyuiop')
    curs=co.cursor()

    curs.execute('''DROP TABLE IF EXISTS CO_DEUX;''')

    curs.execute('''
        CREATE TABLE CO_DEUX(
            entity varchar(150) NOT NULL,
            code varchar(20),
            year numeric(4) NOT NULL,
            emission numeric,
            PRIMARY KEY(entity, year)
        );
    ''')

    for row in df2.itertuples():
        curs.execute(
        '''INSERT INTO CO_DEUX VALUES(%s,%s,%s,%s)''',
        (row.Entity, row.Code, row.Year, row.Emissions)
        )


    df = pd.read_sql('''SELECT * FROM CO_DEUX;''', con=co)
    
    co.commit()
    curs.close()

except (Exception, psy.DatabaseError) as error :
    print(error)

finally :
    if co is not None:
        co.close()
