I'm trying to find a way to use the row number of a table in postgreSQL, using Python. So in a for loop, when the table row number is 22, do something.
Let me show you an easy example:
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
obviously the expression "data.row_number" does not exist and produces an error...
Somebody could help me?
Thanks
You could try with the ROW_NUMBER()
function, for example:
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
simple solution is using the enumerate
:
for row_number, data in enumerate(rows, 1):
if row_number == 22:
您可以从文档中尝试ROW_NUMBER()方法
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.