2012-10-02 25 views
10

我有這個光標錯誤:光標 '對象有沒有屬性' _last_executed

cursor.execute("SELECT price FROM Items WHERE itemID = ( 
        SELECT item_id FROM Purchases 
        WHERE purchaseID = %d AND customer_id = %d)", 
        [self.purchaseID, self.customer]) 

我得到這個錯誤

'Cursor' object has no attribute '_last_executed' 

但當我嘗試這個辦法:

cursor.execute("SELECT price FROM Items WHERE itemID = ( 
        SELECT item_id FROM Purchases 
        WHERE purchaseID = 1 AND customer_id = 1)", 
       ) 

有沒有錯誤。我該如何解決?

+0

你終於得到它的工作雙%%的呢? – juankysmith

+3

我有相同的錯誤消息,但使用ORM。事實證明,charset問題用unicode()封裝我的字符串解決了。我知道它不能回答你的問題,但它可能適合於登陸本頁尋找答案的其他人。 –

+0

感謝張貼,湯米,肯定幫我 – Steve

回答

5

問題是您沒有在您的選擇字符串中正確地進行替換。從文檔:

def execute(self, query, args=None): 

    """Execute a query. 

    query -- string, query to execute on server 
    args -- optional sequence or mapping, parameters to use with query. 

    Note: If args is a sequence, then %s must be used as the 
    parameter placeholder in the query. If a mapping is used, 
    %(key)s must be used as the placeholder. 

    Returns long integer rows affected, if any 

    """ 

所以,它應該是:

cursor.execute("SELECT price FROM Items WHERE itemID = ( 
       SELECT item_id FROM Purchases 
       WHERE purchaseID = ? AND customer_id = ?)", 
       (self.purchaseID, self.customer)) 
+0

它仍然會產生相同的錯誤。 – skinnyas123

+0

你使用的是什麼版本的Python? – juankysmith

+0

我正在使用Python 2.7.2+ – skinnyas123

8

我遇到這個問題了。我將%d更改爲%s,然後解決。希望這對你有用。

+0

這對我有用。我猜你必須通過'%s'即使是整數。 – user2233706

2

原因是您正在使用'%d'。當你在SQL中使用'%'時,execute會將'%'解釋爲格式。你應該寫你的說法是這樣的:

cursor.execute("SELECT price FROM Items WHERE itemID = ( 
       SELECT item_id FROM Purchases 
       WHERE purchaseID = %%d AND customer_id = %%d)", 
       [self.purchaseID, self.customer]) 
+0

我遇到了同樣的問題,但[原始查詢]的文檔(https://docs.djangoproject.com/en/1.5/topics/db/sql/#executing-custom-sql-directly)說要使用一個'%'代替。 – user2233706

+0

這對我在類似情況下工作 – Himanshu

1

逼着我使用

"SELECT title, address from table t1, table t2 on t1.id=t2.id where t1.title like '%%Brink%%' " 
+1

對於低估這一點的人,謹慎解釋爲什麼? – Ram

相關問題