【问题标题】:Retrieve data from sql server database using Python使用 Python 从 sql server 数据库中检索数据
【发布时间】:2019-01-20 01:22:52
【问题描述】:

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

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

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

【问题讨论】:

    标签: python sql sql-server tsql


    【解决方案1】:

    您必须使用 fetch 方法和 cursor。例如

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

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

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

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

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

    Documentation

    【讨论】:

    • 它可以工作,但我想知道只使用 cursor 和 cursor.fetchall() 有什么区别,因为在某些示例中,只有 cursor 与 cursor.fetchall() 相同?
    • cursor 只是一个指向数据库的指针。执行查询后,我们显式地获取了受查询影响的行,因此我们使用 fetchall() 方法来执行此操作。
    • 我的意思是可以只遍历裸光标对象吗?
    • 据我所知,你不能。它最终会导致 RunTimeError
    • 我会继续寻找原因,我知道这可能是因为我一直在使用它,而且我知道它对大型结果集很有效。一旦我发现了一些东西,我会分享它:),
    【解决方案2】:

    我发现此信息对于将数据从 SQL 数据库检索到 python 作为数据框很有用。

    import pandas as pd
    import pymssql
    
    con = pymssql.connect(server='use-et-aiml-cloudforte-aiops- db.database.windows.net',user='login_username',password='login_password',database='database_name')
    cursor = con.cursor()
    
    query = "SELECT * FROM <TABLE_NAME>"
    cursor.execute(query)
    df = pd.read_sql(query, con)
    con.close()
    
    df
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-25
      • 1970-01-01
      • 1970-01-01
      • 2014-01-05
      相关资源
      最近更新 更多