【问题标题】:Inserting into a table with a serial column using psycopg2使用 psycopg2 插入具有串行列的表
【发布时间】:2019-10-21 09:14:16
【问题描述】:

我在 PostgreSQL 中有两个通过 pgAdmin4 创建的简单表:

表1:

CREATE TABLE public.table1
(
    id serial,
    name text,
    PRIMARY KEY (id)
)

表2:

CREATE TABLE public.table2
(
    fk_id integer,
    name text,
    PRIMARY KEY (name),
    CONSTRAINT fk FOREIGN KEY (fk_id)
        REFERENCES public.table1 (id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
)

使用引用第一个表的外键创建第二个表后,table1 中的数据类型 id 会自动更改为整数:

如果我尝试手动将类型更改为串行,则找不到。

并且还使用 psycopg2 这个插入工作:

connection = psycopg2.connect(user = "user",
                              password = "pass",
                              host = "localhost",
                              port = "5432",
                              database = "db")

cursor = connection.cursor()

postgres_insert_query = """INSERT INTO table1 (id,name) VALUES (%s,%s)"""
record_to_insert = (1,'sometext')
cursor.execute(postgres_insert_query, record_to_insert)

connection.commit()

但是这个失败了:

postgres_insert_query = """INSERT INTO table1 (name) VALUES (%s)"""
record_to_insert = ('sometext')

打印此错误:“并非所有参数都在字符串格式化期间转换”

【问题讨论】:

  • postgresql.org/docs/current/… 阅读有关串行类型的部分。 TL;DR serial 不是真正的类型,只是用序列定义整数列的简写方式。
  • 您希望增加什么?如果您定义的表只包含一列,则插入任何内容都只会在该 id 列中,这意味着它不会使用序列,因此不会增加任何内容。
  • 但是当我插入一个新值时,我希望它会自动递增:“INSERT INTO table1 (name) VALUES ('somtext')” “INSERT INTO table1(id,name)VALUES(1,”sometext“)”
  • 该错误与 Postgres 无关,因为普通 SQL 有效:rextester.com/FBVW93753
  • 插入失败,因为您没有创建元组。试试record_to_insert = ('sometext',)

标签: python postgresql psycopg2


【解决方案1】:

我只是错过了@Jeremy 评论的逗号

record_to_insert = ('sometext',)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 2021-12-31
    • 2023-03-10
    • 1970-01-01
    • 2022-01-01
    相关资源
    最近更新 更多