2011-05-29 16 views
2

我正在使用Python 2.6.4及其模塊sqlite3爲一個小型的數據庫項目,我有以下問題:我試圖使用用戶定義的函數,定義的函數,我的意思是,你在Python中定義的函數在查詢之後使用。該函數是另一個模塊中其他函數的包裝器。問題是,當執行查詢時,我總是得到一條異常的消息:'builtin_function_or_method'對象沒有屬性'execute',我不知道爲什麼。代碼如下。你能指出我做錯了什麼嗎?嘗試在sqlite3中使用python使用用戶定義函數的異常

在此先感謝。

包裝功能:

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

回答

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' 對象沒有屬性'執行'

+0

沒錯,男人。我仍然無法讓它運行。但這是一個好的開始。我不敢相信我在**那個錯誤上花了這麼多時間。謝謝。你知道,有時4個眼睛看上去超過2個。 – dagilpe 2011-05-29 12:08:34

+0

我不得不做的其他事情,僅僅爲了別人的參考,就是把名字作爲一個元組來傳遞。最初它是一個字符串,但是需要一個元組來進行參數化。 – dagilpe 2011-05-29 12:12:00