[英]How to update column value in Postgres table from Python based on condition
I have postgres table (Alpha)
with following values我有具有以下值的 postgres 表(Alpha)
Alpha Α
ID Exp_Date Active_Status
1 7-12-2021 active
2 8-12-2021 active
3 15-12-2021 active
4 15-12-2021 active
5 11-12-2021 expired
6 1-12-2021 expired
7 6-12-2021 expired
My Connection String我的连接字符串
postgres_str = f'postgresql://{username}:{password}@{host}:{port}/{dbname}'
# Create the connection and cursor
rds_conn = psycopg2.connect(postgres_str)
rds_cur = rds_conn.cursor()
I want to update the Active_Status
to expired based on two conditions我想根据两个条件将Active_Status
更新为已过期
Exp_date
is less than system date ( todays date)
如果Exp_date
小于system date ( todays date)
Active_Status ='active'
如果Active_Status ='active'
Expected Output预计 Output
ID Exp_Date Active_Status
1 7-12-2021 expired
2 8-12-2021 expired
3 15-12-2021 active
4 15-12-2021 active
5 11-12-2021 expired
6 1-12-2021 expired
7 6-12-2021 expired
How could the update query written from python for postgres从 python 为 postgres 编写的更新查询如何
I would learn to stay away from f strings when working with databases.在使用数据库时,我会学会远离 f 字符串。 I would suggest make_dsn我会建议make_dsn
It is just a SQL query, Python does not really enter in to it.它只是一个 SQL 查询,Python 并没有真正进入它。 Test in psql:在 psql 中测试:
BEGIN;
update
"Alpha"
set
"Active_Status" = 'expired'
where
"Exp_date" < current_date
and
"Active_Status" = 'active';
--Then either COMMIT; or ROLLBACK; depending on whether it worked or not.
Then you can transfer the query to your psycopg2 code.然后您可以将查询转移到您的 psycopg2 代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.