Pyodbc - 打印前 10 行 (python)

Pyodbc - print first 10 rows (python)

我正在尝试使用 pyodbc 打印前 10 行。我知道如何使用以下方法获取第一条记录:

row = cursor.fetchall()

我尝试将其更改为:

row = cursor.fetchten()

但这没有用。还有什么我可以做的吗??

您插入:

row = cursor.fetchmany(10)

您可以将括号中的数字更改为您想要的任何值。

根据找到的文档 on this page,您有两个返回列表的选项。您有 fetchall() 方法和 fetchmany() 方法。在任何一种情况下,您都会返回要处理的行列表。

关于 fetchall() 方法和 zondo 所说的搭载,以下方法快速有效:

rows = cursor.fetchall()[:10] # to get the first 10
rows = cursor.fetchall()[-10::1] # to get the last 10

或者,您可以根据需要循环遍历行以获得所需的结果:

rows = cursor.fetchall()
for idx in range(10): #[0, 1, ..., 9,] 
    print(rows[idx]) # to get the first 10
    print(rows[(len(ray)-idx)]) # to get the last 10

同文档中还有fetchmany()方法,定义如下:cursor.fetchmany([size=cursor.arraysize]) --> list

中括号表示可选参数,因此您无需包含尺寸。但是因为你想要 10,所以你会将 10 传递给 size 参数。示例:

rows = cursor.fetchmany(size=10)
for row in rows:
    print(row)