![](/img/trans.png)
[英]update a row of a table using a second row stacked in a Json, Python and Postgresql
[英]How to detect and use the row number of a table in postgreSQL, using Python?
我正在尝试找到一种使用 Python 在 postgreSQL 中使用表的行号的方法。 所以在 for 循环中,当表行号为 22 时,做一些事情。
让我给你看一个简单的例子:
conn = psycopg2.connect(database=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST, port=DB_PORT)
cur = conn.cursor()
cur.execute("SELECT a, b FROM table")
rows = cur.fetchall()
for data in rows:
if data.row_number == 22:` #if the table row number is 22...
do something
显然表达式“data.row_number”不存在并产生错误......
有人可以帮助我吗?
谢谢
您可以尝试使用ROW_NUMBER()
函数,例如:
conn = psycopg2.connect(database=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST, port=DB_PORT)
cur = conn.cursor()
cur.execute("SELECT a, b, ROW_NUMBER () OVER (ORDER BY a) FROM table")
rows = cur.fetchall()
for data in rows:
if data[2] == 22: #if the table row number is 22...
# do something
简单的解决方案是使用enumerate
:
for row_number, data in enumerate(rows, 1):
if row_number == 22:
您可以从文档中尝试ROW_NUMBER()方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.