Exception when trying to use an user-defined function in sqlite3 using python
I'm using Python 2.6.4 and its module sqlite3 for a small database project and I have the following problem: I'm trying to use a user-defined function, I mean, a function that you define in Python to use after inside your queries. The function is a wrapper for other function I have in another module. The problem is that when doing the query, I always get an AttributeError exception with the message: 'builtin_function_or_method' object has no attribute 'execute' and I have no clue why. The code is the following. Could you point me what I'm doing wrong?
Thanks in advance.
Wrapper function:
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
Function that actually does the query. Note the use of "create_function" method of the Connection object.
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
And finally, the query. It is inside the module ca开发者_运维知识库lled "specificConf". So it is used correctly in the function above, the problem is not there.
SQL_SELECT_ARTIST_SIMILARNAME = u'''
SELECT CODARTIST, NAME, NUMCD, ARESIMILAR(?, NAME) AS SIMILAR
FROM ARTIST
WHERE SIMILAR = 1
'''
cur = con.cursor # sets `cur` to a method
should be
cur = con.cursor() # calls the method and sets `cur` to the return value
This is why you were getting the error saying cur
has no execute
attribute:
AttributeError exception with the message: 'builtin_function_or_method' object has no attribute 'execute'
精彩评论