![](/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.