[英]How to insert sql a row which contains 2 foreign keys?
I have 3 tables:我有3张桌子:
event,event_type,patient
both event_type and patient are foreign keys for event table. event_type 和patient 都是事件表的外键。
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:我有一个 csv 文件 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?有朋友可以帮忙吗?
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
.假设event_type
和patient
已经有正确的信息,那么你可以INSERT
没有patient_name
(如由覆盖patient_id
),并输入patient_id
值到patient
的现场event
。 This would be easier if you used csv.DictReader
from csv then you could do something like:如果您使用来自csv 的csv.DictReader
,这会更容易,然后您可以执行以下操作:
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'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.