插入只有一个串行列的表实际上并没有插入任何内容

时间:2019-01-31 20:26:07

标签: postgresql insert psycopg2

我有一个带有下表的postgres数据库:

CREATE TABLE stocks 
    (
       id serial PRIMARY KEY
    );

和另一个如下表:

CREATE TABLE stock_attributes 
    (
       id serial PRIMARY KEY,
       market_id TEXT,
       short_name TEXT,
       full_name TEXT,
       isin TEXT,
       stock_id serial REFERENCES stocks(id)
    );

这是我进行规范化的尝试,因此,如果错了,请原谅我,但是,我试图在stocks表中插入新行,然后在第二个表中的另一个插入项上使用id:

INSERT INTO stocks DEFAULT VALUES RETURNING id;

查询通过,并返回一个新的ID,但是当我在stock_attributes表中运行第二个查询时,我收到一个错误,指出stock表上不存在关系ID。

INSERT INTO stock_attributes AS a (market_id, short_name, full_name, isin, stock_id) VALUES (%s, %s, %s, %s, %s);

这失败了

insert or update on table "stock_attributes" violates foreign key constraint "stock_attributes_stock_id_fkey"
DETAIL:  Key (stock_id)=(3) is not present in table "stocks".

我正在将psycopg2与python配合使用。

这是代码,几乎是从postgres python指南中复制的:


def execute(sql,args):
    conn = None
    try:
        # read database configuration
        params = config()
        # connect to the PostgreSQL database
        conn = psycopg2.connect(**params)
        # create a new cursor
        cur = conn.cursor()
        cur.execute(sql, args)
        conn.commit()
        # close communication with the database
        cur.close()
        print("SQL executed")
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()

def execute_and_return(sql, args):
    """ insert a new vendor into the vendors table """
    conn = None
    rows = None
    try:
        # read database configuration
        params = config()
        # connect to the PostgreSQL database
        conn = psycopg2.connect(**params)
        # create a new cursor
        cur = conn.cursor()
        cur.execute(sql, args)
        rows = cur.fetchall()
        # close communication with the database
        cur.close()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()
    return rows

1 个答案:

答案 0 :(得分:0)

您对stocks表的键引用不正确。你有:

stock_id serial REFERENCES stocks(id)

应该在什么时候出现:

 stock_id integer REFERENCES stocks(id)

Serial创建一个类型为integer的序列,并将列类型设置为integer,默认值为nextval("<generated sequence name>")。如果您将外键的类型从serial更改为integer,则应该可以使用。