Unable to insert nested record in postgres

∥☆過路亽.° 提交于 2021-01-29 05:40:16

问题


i had managed to create tables in postgres but encountered issues when trying to insert values.

comands = (
CREATE TYPE student AS ( 
   name TEXT,
   id  INTEGER
)

CREATE TABLE studentclass( 
    date DATE NOT NULL,
    time TIMESTAMPTZ NOT NULL, 
    PRIMARY KEY (date, time), 
    class student
)
)
And in psycog2

command = (
INSERT INTO studentclass (date, time, student) VALUES (%s,%s, ROW(%s,%s)::student)
)


student_rec = ("John", 1)
record_to_insert = ("2020-05-21", "2020-05-21 08:10:00", student_rec)
cursor.execute(commands, record_to_insert)

When executed, the errors are the incorrect argument and if i tried to hard coded the student value inside the INSERT statement, it will inform me about the unrecognized column for student.

Please advise.


回答1:


One issue is the column name is class not student. Second is psycopg2 does tuple adaption as composite type

So you can do:

insert_sql = "INSERT INTO studentclass (date, time, class) VALUES (%s,%s,%s)"
student_rec = ("John", 1)
record_to_insert = ("2020-05-21", "2020-05-21 08:10:00", student_rec)
cur.execute(insert_sql, record_to_insert)
con.commit()

select * from studentclass ;
    date    |          time           |  class   
------------+-------------------------+----------
 05/21/2020 | 05/21/2020 08:10:00 PDT | (John,1)




来源:https://stackoverflow.com/questions/64897680/unable-to-insert-nested-record-in-postgres

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!