Reputation: 77
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
Upvotes: 1
Views: 911
Reputation:
simple solution is using the enumerate
:
for row_number, data in enumerate(rows, 1):
if row_number == 22:
Upvotes: 1
Reputation: 15209
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
Upvotes: 1