Postgresql 无法在postgres中插入嵌套记录
我曾设法在postgres中创建表,但在尝试插入值时遇到了问题Postgresql 无法在postgres中插入嵌套记录,postgresql,psycopg2,Postgresql,Psycopg2,我曾设法在postgres中创建表,但在尝试插入值时遇到了问题 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 psyc
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)
执行时,错误是不正确的参数,如果我试图在INSERT语句中硬编码student值,它将通知我student的未识别列
请告知。一个问题是列名是
类
而不是学生
。第二个是psycopg2
doestuple
adaption as
因此,您可以:
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)
在不了解Python的情况下,我假设整个
学生记录将作为单个%s
提供。让record\u to\u insert
有4个成员。这不管用吗:record\u to\u insert=(“2020-05-21”,“2020-05-21 08:10:00”,“John”,1)
?如果您能在这方面提供帮助,我们将不胜感激。非常感谢。