使用psycopg2插入到有序列列的表中

1 人关注

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

CREATE TABLE public.table1
    id serial,
    name text,
    PRIMARY KEY (id)
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

在创建这个带有外键引用第一个表的第二个表后,表1的数据类型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')

打印这个错误。"在字符串格式化过程中没有转换所有参数"