1

我在尝试使用函数使用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 连接作为输入参数传递时,都会发生这种情况。

谢谢

4

1 回答 1

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"""

有关换行的更多信息,请参阅样式指南的最大行长部分

于 2012-05-21T12:20:37.317 回答