我有一个postgres数据库,我使用psycopg2
库通过Python访问。我试图插入的表格如下所示:
Table "public.programmes"
Column | Type | Modifiers | Storage | Stats target | Description
-------------+-----------------------------+---------------------------------------------------------+----------+--------------+-------------
id | bigint | not null default nextval('programmes_id_seq'::regclass) | plain | |
title | character varying | not null | extended | |
start | timestamp without time zone | not null | plain | |
end | timestamp without time zone | not null | plain | |
description | character varying | not null | extended | |
genre | character varying | not null | extended | |
edited | boolean | not null | plain | |
id
列已创建为bigserial
到autoincrement个新条目。
由于id
列会自动增量,我只会尝试插入有关其余字段的数据。我将数据创建为列表并尝试插入它:
def main():
postConn = psycopg2.connect("dbname=TEST host=127.0.0.1 user=user")
postCur = postConn.cursor()
prog_data = form_programme_data()
#prog_data = ['The Next Step', '2016-05-29T10:20:00', '2016-05-29T10:45:00', "2/34. My Boyfriend's Back: Reality-style drama following a group of dancers. A-Troupe meets their new choreographer and votes for open auditions for the nationals team. Also in HD. [S]", 'Lifestyle', False]
postCur.execute("""INSERT INTO programmes(title, start, end, description, genre, edited) VALUES (%s, %s, %s, %s, %s, %s);""", prog_data)
我被抛出这个错误:
Traceback (most recent call last):
File "convert_db.py", line 58, in <module>
main()
File "convert_db.py", line 32, in main
postCur.execute("""INSERT INTO programmes(title, start, end, description, genre, edited) VALUES (%s, %s, %s, %s, %s, %s);""", prog_data)
psycopg2.ProgrammingError: syntax error at or near "end"
LINE 1: INSERT INTO programmes(title, start, end, description, genre...
^
如果我尝试在不指定列名的情况下插入,则它需要id
的值,我无法触及。它没有抱怨提供的前两个列名,但由于某种原因不喜欢end
。
感谢任何帮助。
答案 0 :(得分:2)
显然,end
是PostgreSQL中的key word。您需要引用它以使其被解释为标识符:
postCur.execute("""INSERT INTO programmes
(title, start, "end", description, genre, edited)
VALUES (%s, %s, %s, %s, %s, %s);""", prog_data)
答案 1 :(得分:1)
我很确定end
是Postgres中的保留关键字。尝试将列名更改为其他名称 - 这肯定会解决问题。或者,延迟解决方案可能要更改您的代码:
postCur.execute("""INSERT INTO programmes('title', 'start', 'end', 'description', 'genre', 'edited') VALUES (%s, %s, %s, %s, %s, %s);""", prog_data)
看看它是否解决了您的问题并告诉我们。