我正在运行以下版本的软件:
Python 3.5
psycopg2==2.6.1
Postgres 9.4.5
我有2张桌子。表User
包含UserId (serial PK)
,LastName
,FirstName
,Gender
,DateOfBirth
和DateEnrolled
。表UserProfile
包含UserProfileId (serial, PK)
,UserId (FK)
,DateEntered
,FaveNumber
和Activity
。有一对多的关系。
以下PostgreSQL可以工作并最终在UserProfile中创建一个带有关联UserId(FK)的记录。
\set last_name '''Sara'''
\set first_name '''Jackson'''
\set gender '''F'''
\set dob '''1941-1-12'''
\set fave_number '''3'''
\set activity '''volleyball'''
WITH ins_user AS (
INSERT INTO User
(LastName, FirstName, Gender, DateOfBirth, DateEnrolled)
VALUES (:last_name, :first_name, :gender, :dob, now())
RETURNING UserId)
INSERT INTO UserProfile
(UserId, DateEntered, FaveNumber, Activity)
VALUES ( (SELECT UserId FROM ins_user), now(), :fave_number :activity);
如何构建一个能完成上述PostgreSQL的psycopg2 cur.execute查询?我已经阅读了文档,但似乎无法理解我应该如何构建此命令。
我的出发点是:
cur.execute( \
"""INSERT INTO User \
(LastName, FirstName, Gender, DateOfBirth, DateEnrolled) \
VALUES (%s, %s, %s, %s, %s) RETURNING UserId;""", \
(last_name, first_name, gender, date_of_birth, now(), ??...??)
此外,是否可以提取从RETURNING UserId
派生的值,以便可以在以后的查询中使用?
感谢您的时间!
答案 0 :(得分:1)
使用字典传递参数
更清楚ins = """
with ins_user as (
insert into User (
LastName, FirstName, Gender, DateOfBirth, DateEnrolled
) values (%(last_name)s, %(first_name)s, %(gender)s, %(dob)s, now())
returning UserId
)
insert into UserProfile (
UserId, DateEntered, FaveNumber, Activity
) values ((select UserId from ins_user), now(), %(fave_number)s, %(activity)s)
"""
ins_dict = dict (
last_name = 'Sara',
first_name = 'Jackson',
gender = 'F',
dob = '1941-1-12',
fave_number = '3',
activity = 'volleyball'
)
print cur.mogrify(ins, ins_dict) # inspect the rendered command
cur.execute(ins, ins_dict)
connection.commit()
如果DateEnrolled
始终收到now()
,请将其设为默认
DateEnrolled date default now(),
答案 1 :(得分:-1)
cur.execute( \
"""INSERT INTO User \
(LastName, FirstName, Gender, DateOfBirth, DateEnrolled) \
VALUES (%s, %s, %s, %s, %s) RETURNING UserId;""", \
(last_name, first_name, gender, date_of_birth, now(), ??...??)