簡體   English   中英

如何使用 Python 在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM