Home > other >  How to insert sql a row which contains 2 foreign keys?
How to insert sql a row which contains 2 foreign keys?

Time:11-11

I have 3 tables:

event,event_type,patient

both event_type and patient are foreign keys for event table.

event fields:id, event_type(foreign key),event_unit, event_value,event_time, patient(foreign key)

event_type fields: id, name

patient fields : patient_id ,patient_name

and I have a csv file events.csv:

import csv
with open(r'/Users/williaml/Downloads/events.csv') as csvfile: 
    spamreader = csv.reader(csvfile, delimiter=',' ,quotechar=' ')
    for row in spamreader:
        print(row)

the output is:

['"PATIENT ID', 'PATIENT NAME', 'EVENT TYPE', 'EVENT VALUE', 'EVENT UNIT', 'EVENT TIME"']
['"1', 'Jane', 'HR', '82', 'beats/minute', '2021-07-07T02:27:00Z"']
['"1', 'Jane', 'RR', '5', 'breaths/minute', '2021-07-07T02:27:00Z"']
['"2', 'John', 'HR', '83', 'beats/minute', '2021-07-07T02:27:00Z"']
['"2', 'John', 'RR', '14', 'breaths/minute', '2021-07-07T02:27:00Z"']
['"1', 'Jane', 'HR', '88', 'beats/minute', '2021-07-07T02:28:00Z"']
['"1', 'Jane', 'RR', '20', 'breaths/minute', '2021-07-07T02:28:00Z"']
['"2', 'John', 'HR', '115', 'beats/minute', '2021-07-07T02:28:00Z"']
['"2', 'John', 'RR', '5', 'breaths/minute', '2021-07-07T02:28:00Z"']

Now I want to insert these rows into database:

import psycopg2
conn = psycopg2.connect(host='localhost', dbname='patientdb',user='username',password='password',port='')
cur = conn.cursor()

    import csv
with open(r'/Users/williaml/Downloads/events.csv') as csvfile: 
    spamreader = csv.reader(csvfile, delimiter=',' ,quotechar=' ')
    for row in spamreader:
            INSERT INTO event (patient_id, patient_name, event_type, event_value ,event_unit, event_time) VALUES ( row[0],row[1],row[3],row[4],row[5])

Received error:

psycopg2.errors.UndefinedColumn: column "patient_name" of relation "event" does not exist

I think the reason is I can't directly insert the whole row ,because the values belong to different tables.

Any friends can help?

CodePudding user response:

Assuming event_type and patient already have the correct information then you could INSERT without patient_name(as that is covered by patient_id) and enter the patient_id values into the patient field in event. This would be easier if you used csv.DictReader from csv then you could do something like:

INSERT INTO 
    event (patient, event_type, event_value ,event_unit, event_time) VALUES 
  (row['PATIENT ID'],row['EVENT TYPE'],row['EVENT VALUE'],
   row['EVENT UNIT'],row['EVENT TIME'])
  • Related