[英]How to detect and use the row number of a table in postgreSQL, using Python?
I'm trying to find a way to use the row number of a table in postgreSQL, using Python.我正在尝试找到一种使用 Python 在 postgreSQL 中使用表的行号的方法。 So in a for loop, when the table row number is 22, do something.
所以在 for 循环中,当表行号为 22 时,做一些事情。
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...显然表达式“data.row_number”不存在并产生错误......
Somebody could help me?有人可以帮助我吗?
Thanks谢谢
You could try with the ROW_NUMBER()
function, for example:您可以尝试使用
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
simple solution is using the enumerate
:简单的解决方案是使用
enumerate
:
for row_number, data in enumerate(rows, 1):
if row_number == 22:
您可以从文档中尝试ROW_NUMBER()方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.