Postgresql 使用psycopg2在postgres中调用当前_TIMESTAMP()
我有一个postgresql表,用来存储两个时间戳。第一个时间戳在订单启动时插入,第二个时间戳在订单状态返回时更新Postgresql 使用psycopg2在postgres中调用当前_TIMESTAMP(),postgresql,psycopg2,Postgresql,Psycopg2,我有一个postgresql表,用来存储两个时间戳。第一个时间戳在订单启动时插入,第二个时间戳在订单状态返回时更新 CREATE TABLE IF NOT EXISTS orders ( order_id SERIAL PRIMARY KEY, purchase_id INTEGER NOT NULL, requested_amount INTEGER NOT NULL, order_submitted_date TIMESTAMP NOT NULL DE
CREATE TABLE IF NOT EXISTS orders
(
order_id SERIAL PRIMARY KEY,
purchase_id INTEGER NOT NULL,
requested_amount INTEGER NOT NULL,
order_submitted_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
order_confirmed_date TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
confirm_num INTEGER NULL
);
我的理解是,TIMESTAMP
是类型,而CURRENT\u TIMESTAMP
是被调用以创建时间戳的函数
我的困惑在于:当我插入并更新一行时,我是否需要做任何事情来调用CURRENT\u TIMESTAMP
函数,还是自动执行
'INSERT INTO orders (purchase_id, requested_amount) \
VALUES (%s, %s) RETURNING order_id;',
(purchId, requestedAmount)
'UPDATE orders SET (confirm_num) VALUES (%s) WHERE order_id = %s',
(confirm_num, row_id)
当您插入行时,Postgres将自动插入
当前时间戳
,并且不使用默认
选项为字段指定值
更新行时,如果要更改值,则必须显式指定这些值。因此,您的表应该如下所示:
CREATE TABLE IF NOT EXISTS orders
(
order_id SERIAL PRIMARY KEY,
purchase_id INTEGER NOT NULL,
requested_amount INTEGER NOT NULL,
order_submitted_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
order_confirmed_date TIMESTAMP,
confirm_num INTEGER NULL
);
和更新查询:
'UPDATE orders \
SET (order_confirmed_date, confirm_num) = (current_timestamp, %s) \
WHERE order_id = %s',
(confirm_num, row_id)
now()postgres函数使用psycopg2 python包处理insert语句
--Table Create Statement (SQL)
create table temp.current_timestamp_stream_test
(today_dts TIMESTAMP WITH TIME ZONE NOT NULL,
random_val varchar(200));
因此,当第一次插入行时,我的第二个时间戳(订单确认日期)仍然为空。为了更新它,我需要将我的
update
调用更改为'updateorders SET(order\u confirm\u date,confirm\u num)值(%s,%s),其中order\u id=%s',(order\u confirm\u date,confirm\u num,row\u id)
。我还必须删除订单确认日期的默认值,以便在第一次插入表时保持为空?哎呀,应该更新“更新订单集(订单确认日期,确认数量)”值(%s,%s),其中订单id=%s',(当前时间戳(),确认数量,行id)
?“更新订单集”(订单确认日期,确认编号)值(当前时间戳,%s),其中订单id=%s',(确认编号,行id)
oh ok。然后删除默认值?是,删除订单确认日期的默认值。
#Python3 to execute
import psycopg2
conn = psycopg2.connect(database = _xxx,
host = _xxx,
port = _xxx,
user = _xxx,
password = _xxx)
cur = conn.cursor()
cur.execute("""
insert into temp.current_timestamp_stream_test
(today_dts, random_val)
select now(), 'today';
""")
conn.commit()