尝试使用python在sqlite3中使用用户定义的函数时出现异常

时间:2011-05-29 11:55:08

标签: python sqlite

我正在使用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 个答案:

答案 0 :(得分: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'   object没有属性'execute'