如何使用Python在postgreSQL中检测和使用表的行号?

2024-04-25 10:09:08 发布

您现在位置: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”不存在并产生错误

有人能帮我吗

谢谢


Tags: 方法numberfordbdataifpostgresqltable
3条回答

您可以尝试文档中的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:

相关问题 更多 >