使用 Python 从 sql server 数据库中检索数据

Moh*_*izi 3 python sql t-sql sql-server

我正在尝试执行以下脚本。但我既没有得到想要的结果,也没有得到错误消息,而且我不知道我做错了什么。

import pyodbc 
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                        "Server=mySRVERNAME;"
                        "Database=MYDB;"
                        "uid=sa;pwd=MYPWD;"
                        "Trusted_Connection=yes;")


cursor = cnxn.cursor()
cursor.execute('select DISTINCT firstname,lastname,coalesce(middlename,\' \') as middlename from Person.Person')

for row in cursor:
    print('row = %r' % (row,))
Run Code Online (Sandbox Code Playgroud)

有任何想法吗 ?任何帮助表示赞赏:)

Har*_*nan 5

您必须将 fetch 方法与游标一起使用。例如

for row in cursor.fetchall():
    print('row = %r' % (row,))
Run Code Online (Sandbox Code Playgroud)

编辑 :

fetchall 函数返回列表中所有剩余的行。

    If there are no rows, an empty list is returned. 
    If there are a lot of rows, *this will use a lot of memory.* 
Run Code Online (Sandbox Code Playgroud)

未读行由数据库驱动程序以紧凑格式存储,通常从数据库服务器批量发送。

一次只读入您需要的行将节省大量内存

如果我们要一次处理一行,我们可以使用游标本身作为一个interator 而且我们可以简化它,因为 cursor.execute() 总是返回一个游标:

for row in cursor.execute("select bla, anotherbla from blabla"): 
    print row.bla, row.anotherbla
Run Code Online (Sandbox Code Playgroud)

文档