2012-09-29 57 views
0

我通常使用Django ORM製作的蟒蛇數據庫相關的查詢,但現在我使用Python本身Python數據庫更新錯誤

我試圖更新我的MySQL數據庫的行

query ='UPDATE callerdetail SET upload="{0}" WHERE agent="{1}" AND custid="{2}"AND screenname="{3}" AND status="1"'.format(get.uploaded,get.agent,get.custid,get.screenname) 

但我得到的錯誤

query ='UPDATE callerdetail SET upload="{0}" WHERE agent="{1}" AND custid="{2}"AND screenname="{3}" AND status="1"'.format(get.uploaded,get.agent,get.custid,get.screenname) 

AttributeError的: 'C' 對象有沒有 '上傳'

屬性

請幫我看看我的查詢出了什麼問題?

回答

0

獲取可能映射到一個c對象。嘗試將你的「get」對象重命名爲別的東西。

以下是reserved words的列表。我沒有看到那裏,但它聽起來像它可能是包含在一個C庫中的一部分。如果您在x import *中包含,那麼您可能會在不知情的情況下導入它。

0

總之 - get可能不是你認爲的那樣。

但是,在進一步構建帶有字符串格式的SQL查詢之前,我強烈建議您不要!搜索「SQL注入」,你會看到爲什麼。符合Python DB API的庫使用「佔位符」,庫可以使用該佔位符將變量插入查詢中,以供您提供任何必要的轉義/引用。

所以不是:

query ='UPDATE callerdetail SET upload="{0}" WHERE agent="{1}" AND custid="{2}"AND screenname="{3}" AND status="1"'.format(get.uploaded,get.agent,get.custid,get.screenname) 

使用SQLite3的一個例子(使用?作爲佔位符 - 其他人使用%s:1或%(名稱)的S - 或任何/所有上述的 - 但是,這會

query = "update callerdetail set upload=? where agent=? and custid=? and screename=? and status=?" 

然後當它涉及到執行查詢,您提供的值代入爲一個單獨的參數:

在庫的文檔)中詳細
cursor.execute(query, (get.uploaded, get.agent, get.custid, get.screenname)) 

如果你真的想要的,你可以有一個方便的功能,這減少:

from operator import attrgetter 
get_fields = attrgetter('uploaded', 'agent', 'custid', 'screenname') 
cursor.execute(query, get_fields(get)) 
+0

爲Python最常見的MySQL數據庫適配器使用'%s'風格的SQL參數(是的,呼應蟒蛇字符串格式化語法)。 –