简体   繁体   English

如何使用 Python 在 postgreSQL 中检测和使用表的行号?

[英]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.

相关问题 使用堆叠在 Json、Python 和 Postgresql 中的第二行更新表的一行 - update a row of a table using a second row stacked in a Json, Python and Postgresql PostgreSQL的。 如何使用python将行中单元格的值复制并粘贴到同一个表中另一行的另一个单元格中 - Postgresql. How to copy the value of a cell in a row and paste it into another cell of another row in the same table using python 如何使用 Python 删除 PostgreSQL 中的行? - How to delete row in PostgreSQL using Python? 使用Python以编程方式检测出现空格的列和行号 - Detect the column and row number where whitespace is occuring using Python programmatically 如何检查 python 中的列表和 PostgreSQL 表中的行是否包含相同的文件? - How to check if a list in python and row in PostgreSQL table contain same files? 如何使用PostgreSQL在Python中理解和使用asyncio? - How to understand and use asyncio in Python using PostgreSQL? Python / PostgreSQL - 如何使用psycopg2库将表复制到另一个表? - Python / PostgreSQL - How to copy a table to another using the psycopg2 library? 如何使用python将CSV数据转储到postgresql表中 - how to dump CSV data into postgresql table using python postgresql中如何将一个表行值更改为另一个表行值 - How to change a table row value to another table row value in postgresql 如何在Python中的PostgreSQL中使用变量 - How to use variables in PostgreSQL in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM