从Python dict批量更新PostgreSQL

编程入门 行业动态 更新时间:2024-10-28 04:18:04
本文介绍了从Python dict批量更新PostgreSQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在一个现有的PostgreSQL表中,我想UPDATE使用字典查找中的值对几个现有的列进行查找(请参见下面的dict).类似于不错的博客帖子中所述的内容.但是,我不知道如何使用Python字典来做到这一点.这是可怕的伪代码:

In an existing PostgreSQL table, I would like to UPDATE several existing columns with values from a dictionary lookup (see dict below). Somewhat like described in this nice blog post. However, I can't figure out how to do that with a Python dictionary. Here comes the terrible pseudo-code:

d = {10:'chair', 11:'table', 12:'lamp', 20:'english ivy', 21:'peace lily', 22:'spider plant'} curs.execute(""" UPDATE my_table t SET furniture = %(t.furniture)s, SET plant = %(t.plant)s""", d)

原始表如下所示:

gid | furniture | plant ----------------------- 0 | 10 | 21 1 | 11 | 20 ...

操作后,它应如下所示:

After the operation it should look like this:

gid | furniture | plant ----------------------------- 0 | chair | peace lily 1 | table | english ivy ...

这可能吗?还是我必须遍历这张桌子?

Is this possible or will I have to loop through the table?

推荐答案

尝试一下:

rows = ( {'gid': 10, 'furniture': 10, 'plant': 10}, {'gid': 20, 'furniture': 20, 'plant': 20} ) cur.executemany( ''' UPDATE myTable SET furniture = %(furniture)s, plant = %(plant)s WHERE gid = %(gid)s ''', rows )

更多推荐

从Python dict批量更新PostgreSQL

本文发布于:2023-10-23 22:22:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1522167.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:批量   Python   dict   PostgreSQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!