psycopg2无法插入特定列

2024-06-07 03:48:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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到{a1}的新条目。在

由于id列将自动递增,所以我只尝试插入有关其余字段的数据。我将数据创建为列表,并尝试按如下方式插入:

^{pr2}$

我被抛出这个错误:

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。在

感谢任何帮助。在


Tags: idextendedtitlenotdescriptionstartnullpsycopg2
2条回答

我很确定end是Postgres中的保留关键字。尝试将列名更改为其他名称-这肯定会解决问题。或者,懒惰的解决方案可能是更改代码:

postCur.execute("""INSERT INTO programmes('title', 'start', 'end', 'description', 'genre', 'edited') VALUES (%s, %s, %s, %s, %s, %s);""", prog_data)

看看能不能解决你的问题,告诉我们。在

显然,end在PostgreSQL中是key word。您需要引用它才能将其解释为标识符:

postCur.execute("""INSERT INTO programmes
    (title, start, "end", description, genre, edited)
    VALUES (%s, %s, %s, %s, %s, %s);""", prog_data)

相关问题 更多 >