Pyodbc - 打印前10行(python)

sem*_*lex 9 python pyodbc fetch

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

row = cursor.fetchall()
Run Code Online (Sandbox Code Playgroud)

我尝试将其更改为:

row = cursor.fetchten()
Run Code Online (Sandbox Code Playgroud)

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

sem*_*lex 6

你插入:

row = cursor.fetchmany(10)
Run Code Online (Sandbox Code Playgroud)

您可以将括号中的数字更改为您想要的任何内容.


ATL*_*LUS 5

根据此页面上的文档,您有两个返回列表的选项。你有fetchall()方法和fetchmany()方法。在任何一种情况下,您都会返回一个要处理的行列表。

关于fetchall()zondo 所说的方法和捎带,以下工作快速有效:

rows = cursor.fetchall()[:10] # to get the first 10
rows = cursor.fetchall()[-10::1] # to get the last 10
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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

括号表示可选参数,因此您不需要包含大小。但是由于您想要 10,您将 10 传递给 size 参数。例子:

rows = cursor.fetchmany(size=10)
for row in rows:
    print(row)
Run Code Online (Sandbox Code Playgroud)