'pandas : how to import dataframe into postgresql database?

df1        
Matricule       Date Hours
    0  10 2022-01-06 0
    1  10 2022-01-07 0
    2  10 2022-01-26 0
    3  14 2022-01-03 0
    4  14 2022-01-04 9
    5  14 2022-01-05 7
    6  14 2022-01-06 6
    7  14 2022-01-07 5
    8  14 2022-01-10 7
    9  14 2022-01-11 6
    10 14 2022-01-12 0
    11 14 2022-01-13 9
    12 14 2022-01-14 6
    13 14 2022-01-17 0
    14 14 2022-01-18 8
    15 14 2022-01-19 8
    16 14 2022-01-20 8
    17 14 2022-01-21 5
    18 14 2022-01-24 9
    19 14 2022-01-25 3
    20 14 2022-01-26 12
    21 14 2022-01-27 10
    22 14 2022-01-28 0

df2
Matricule FirstName Lastname Departement Sexe
10        Ben       aflick   Support     M
14        Angela    Dolberg  Support     F

those are my two dataframes i wanted to load them into postgresql but always the tables in the database are empty , i was wondering how to link them to database although the tables in postgres have different name than the dataframe and this the postgresql tables :tables

i've tried this :

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="test", user='postgres', password='pass', host='localhost', port='5432'
)
  
df2 = pd.read_csv('C:/Users/hp/Desktop/test.csv',sep=";",encoding='latin-1')
  
execute_values(conn, df2, "emp")


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source