我正在查询数据库并显示名称或结果。如果数据库中有几个“Michael”名字,则会显示所有带有姓氏的名字
如果数据库中只有一个Michael,则会显示Michael的全名以及错误“List index out of range”
这是因为我要求程序显示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接口的问题,而是Python的基本机制
您应该使用基本的
for
构造:实际上,它会处理4、1或0的情况
另外,除非您打算在以后的阶段参数化查询,否则您可能需要使用一个变量,因为它是一个“常量”:
相关问题 更多 >
编程相关推荐