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

2024-09-29 19:22:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试执行以下脚本。但我既没有得到想要的结果,也没有得到错误消息,我无法找出我做错了什么。

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,))

有什么想法吗?感谢您的帮助:)


Tags: import脚本消息sqlserverdriverconnect错误
1条回答
网友
1楼 · 发布于 2024-09-29 19:22:06

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

for row in cursor.fetchall():
    print('row = %r' % (row,))

编辑:

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.* 

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

一次只读取所需的行将节省大量内存。

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

for row in cursor.execute("select bla, anotherbla from blabla"): 
    print row.bla, row.anotherbla

Documentation

相关问题 更多 >

    热门问题