I am extracting data from csv to postgres with python. I have used copy_from to input the data from 3 csv's into 3 postgres tables. Now I have to create a 4 table that agrees the results. Would there be a way to extract a specific column from csv with copy_from to insert them into the new table?
Since I already have the data in 3 tables, I was trying to launch a query that merges the data and dumps it into the 4 table.
If someone could advise me to do it in a simple and correct way.
Thank you very much in advance.
Way to do it with copy_from:
modelo = open(r'modelo.csv', 'r')
cursor.copy_from(modelo, 'modelo', sep=';')
connection.commit()
print("Se han introducido correctamente los datos en la tabla Modelo")
color = open(r'color.csv', 'r')
cursor.copy_from(color, 'color', sep=';')
connection.commit()
print("Se han introducido correctamente los datos en la tabla Color")
matricula = open(r'matricula.csv', 'r')
cursor.copy_from(matricula, 'matricula', sep=';')
connection.commit()
print("Se han introducido correctamente los datos en la tabla Matricula")
Way to do it with dataframe:
df =pd.read_csv('modelo.csv', header=None, names=["id", "modelo", "marca"])
df2 = pd.read_csv('color.csv', header=None, names=["id", "idmodelo", "color"])
df3 = pd.read_csv('matricula.csv', header=None, names=["id", "idmodelo", "matricula"])
engine = create_engine('postgresql://user:[email protected]:5432/bbdd')
df.to_sql('modelo', con=engine, if_exists='replace', index=False)
I have not worked with Postgres, but SQL is standard for all DBMS, so with this UPDATE you should achieve your goal, the only requirement for its execution is that you have defined an FK in each table to be able to relate them and of course how it is an UPDATE The index field should already exist in the target table to proceed with the UPDATE.