我有一个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 DEFAULT CURRENT_TIMESTAMP,
order_confirmed_date TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
confirm_num INTEGER NULL
);
我的理解是TIMESTAMP
是类型,而CURRENT_TIMESTAMP
是被调用以创建时间戳的函数。
我的困惑在于:当我插入并更新一行时,是否需要执行任何操作才能调用CURRENT_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)
答案 0 :(得分:0)
Postgres会在您插入行时自动插入current_timestamp
,并且不会为具有default
选项的字段指定值。
更新行时,如果要更改值,则必须明确指定值。所以你的表应该是这样的:
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)
答案 1 :(得分:0)
now()postgres函数可使用psycopg2 python软件包处理插入语句。
--Table Create Statement (SQL)
create table temp.current_timestamp_stream_test
(today_dts TIMESTAMP WITH TIME ZONE NOT NULL,
random_val varchar(200));
#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()