我在使用pyodbc尝试使用函数在MSSQL中查询数据时遇到了麻烦,该函数是:
def getUserList(connection):
li = []
cur = connection.cursor()
query = 'select username, password, firstname, lastname, description, phone,'+
'email, isAdmin, isAutoBoot from users_tbl'
cur.execute(query)
for usr, pwd, fn, ln, des, ph, em, ad, au in cur.fetchall():
temp = User(usr, pwd, fn, ln, des, ph, em, ad, au)
cur.close()
#con.close()
return li
当我导入模块并运行此函数时,它会遇到TypeError:
Traceback (most recent call last):
File "<pyshell#71>", line 1, in <module>
import_user.getUserList(s_con)
File "c:/python27/mymodule\import_user.py", line 12, in getUserList
cur.execute(query)
TypeError: string indices must be integers
但是,如果我在Python IDLE中复制并运行这些行中的每一行,它在运行游标时运行正常并且没有错误。当我将pyodbc或sqlite连接作为输入参数传递时,它就会发生。
由于
答案 0 :(得分:0)
要解决语法问题,请更改以下行:
query = 'select username, password, firstname, lastname, description, phone,'+
'email, isAdmin, isAutoBoot from users_tbl'
到(换行未保留):
query = ('select username, password, firstname, lastname, description, phone, '
'email, isAdmin, isAutoBoot from users_tbl')
或(换行保留):
query = """select username, password, firstname, lastname, description, phone,
email, isAdmin, isAutoBoot from users_tbl"""
有关换行的更多信息,请参阅样式指南的Maximum Line Length section。