python - 仅显示 PyODBC 的可用结果

标签 python pyodbc

我正在查询数据库并显示名称或结果。如果数据库中有多个“Michael”姓名,则显示所有带有姓氏的姓名。

如果数据库中只有 1 个 Michael,则会显示该 Michael 的全名并显示错误“列表索引超出范围”。

这是因为我要求程序显示 4 个名为 Michael 的结果,但只有一个可用。

使用时如何解决这个问题

        for _ in range(0, 4):
            print(str(results[_])) # displays results

这里是一切:

import pypyodbc

def queryfirst():
    return ("SELECT FIRSTNAME, LASTNAME "      
            "FROM dbo.My_Table "
            "WHERE FIRSTNAME = ?")

def sqlfirst():
    firstname = "Michael"
    if True:    
        connection = pypyodbc.connect('Driver={SQL Server};Server=mysSQLserver;Database=MyDatabaseName;Trusted_Connection=yes;')
        cursor = connection.cursor() 
        SQLCommand = queryfirst()
        Values = [firstname]
        cursor.execute(SQLCommand,Values)
        return cursor.fetchmany(4)


def calculate():
    results = sqlfirst()
    if results:
        for _ in range(0, 4):
            print(str(results[_])) # enters results in entry
        connection.close()


calculate()

我不确定如何说“如果结果少于 4,则仅显示可用的结果”。 cursor.fetchmany 或cursor.fetchall 有区别吗?

我需要获取结果的长度吗?

最佳答案

乍一看,这不是 SQL 接口(interface)的问题,而是 Python 的基 native 制。

您应该使用基本的 for 构造:

def calculate():
    results = sqlfirst()
    for r in results:
        print(str(r))

实际上,它会处理 4、1 或 0 的情况。

附注除非您打算在稍后阶段对查询进行参数化,否则您可能需要使用变量,因为它是“常量”:

QUERY_FIRST = "SELECT FIRSTNAME, LASTNAME"      
             "FROM dbo.My_Table"
             "WHERE FIRSTNAME = ?"

关于python - 仅显示 PyODBC 的可用结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49063527/

相关文章:

python - 从 .pyo 文件导入 .pyd 文件(作为 python 模块)时出错

python - SQL查询并不总是插入缺失值

database - 如何创建对 Sage ERP 数据库具有只读访问权限的帐户以与 pyodbc 一起使用

python - 如何使用 python pyodbc 检查表中是否存在列?

python - 如何使用 pyodbc 获取 SQL Server 存储过程返回的行集?

python - 获取 JSON 格式的存储过程结果

python - PyQt OpenGL : drawing simple scenes

python - 在 Python 2.7 中用分号替换命名变量

python - jinja 2 嵌套字典到 yaml

python - 使用另一个二维数组 foo 索引二维数组 bar,其中 foo 包含 bar 相应列的行索引