使用psycopg2插入到具有串行列的表中

2024-04-20 16:25:22 发布

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

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

表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
)

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

image

如果我尝试手动将类型更改为serial,则找不到。你知道吗

使用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')

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


Tags: tokeynameidcreatetablepostgrespublic