gpt4 book ai didi

python postgres 在读取结果时更改行的值

转载 作者:行者123 更新时间:2023-11-29 12:51:09 24 4
gpt4 key购买 nike

我正在使用 python3、postgress 10 和 Psycopg2 来查询多条记录

import psycopg2
conn = psycopg2.connect(<my connection string>)
with conn:
with conn.cursor() as cur:
cur.execute('select id,field1 from table1')
for id, field1 from cur.fetchall():
print(id,field1)
#todo: how up update field1 to be f(field1) where f is an arbitrary python function

我的问题是:我如何更新我正在读取的行的值并将 field1 的值设置为一些基于 python 的任意计算

编辑:目的是更新表中的行

最佳答案

您需要另一个光标,例如:

with conn:
with conn.cursor() as cur:
cur.execute('select id,field1 from table1')
for id, field1 in cur.fetchall():
print(id,field1)
with conn.cursor() as cur_update:
cur_update.execute('update table1 set field1 = %s where id = %s', (f(field1), id))

但是请注意,这涉及与选定行一样多的更新,这显然效率不高。可以使用 psycopg2.extras.execute_values(): 在单个查询中完成更新

from psycopg2.extras import execute_values

with conn:
with conn.cursor() as cur:
cur.execute('select id,field1 from table1')
rows = cur.fetchall()
for id, field1 in rows:
print(id,field1)

# convert rows to new values of field1
values = [(id, f(field1)) for id, field1 in rows]
sql = '''
with upd (id, field1) as (values %s)
update table1 t
set field1 = upd.field1
from upd
where upd.id = t.id
'''
with conn.cursor() as cur:
execute_values(cur, sql, values)

关于python postgres 在读取结果时更改行的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53689149/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com