使用Python在sqlite3中调用用户定义函数时出现异常

2 投票
1 回答
2241 浏览
提问于 2025-04-16 18:33

我正在使用Python 2.6.4和它的sqlite3模块来做一个小型数据库项目,但遇到了一个问题:我想使用一个用户定义的函数,也就是在Python中自己定义的函数,然后在查询中使用。这个函数是一个包装器,用来调用我在另一个模块中的其他函数。问题是,当我执行查询时,总是会出现一个AttributeError错误,提示信息是:'builtin_function_or_method'对象没有'execute'属性,我完全不知道为什么。以下是我的代码。你能告诉我我哪里出错了吗?

提前谢谢你。

包装器函数:

def SQLAreSimilar(userSelectedName, artistName):
    '''
    Wrapper to the areSimilar function of strUtils to use it directly inside the
    queries. Not to be called directly.
    '''
    if strUtils.areSimilar(userSelectedName, artistName):
        return 1
    else:
        return 0

实际执行查询的函数。注意这里使用了Connection对象的"create_function"方法。

def getArtistsBySimilarName(name):
    '''
    Returns all artists with a similar name, according to the Levenshtein
    distance. The DB is supposed to be initialised. Returns a dictionary of
    dictionaries with the data of all similar artists indexed by its CODARTIST,
    the PK. The dictionary is empty if no row is returned. None is returned on
    error.
    '''
    try:
        con = sqlite3.connect(genericConf.SQL_DBNAME)
        con.row_factory = sqlite3.Row
        con.create_function("ARESIMILAR", 2, SQLAreSimilar)
        cur = con.cursor
        rows = cur.execute(specificConf.SQL_SELECT_ARTIST_SIMILARNAME, name)
        retDict = {}
        for row in rows:
            d = {}
            d['NUMCD'] = row['NUMCD']
            d['NAME'] = row['NAME']
            retDict[row['CODARTIST']] = d
        return retDict
    except:
        return None

最后是查询。它在一个叫做"specificConf"的模块里。所以在上面的函数中使用是正确的,问题不在这里。

SQL_SELECT_ARTIST_SIMILARNAME = u'''
SELECT  CODARTIST, NAME, NUMCD, ARESIMILAR(?, NAME) AS SIMILAR
FROM    ARTIST
WHERE   SIMILAR = 1  
'''

1 个回答

2
cur = con.cursor    # sets `cur` to a method

应该是这样的

cur = con.cursor()  # calls the method and sets `cur` to the return value

这就是你为什么会看到错误信息,提示 cur 没有 execute 属性的原因:

出现了一个 AttributeError 异常,信息是:'builtin_function_or_method' 对象没有 'execute' 属性

撰写回答