2013-06-23 71 views
0

在我有下面的代碼的類型麻煩蟒蛇:蟒蛇MySQL的錯誤類型

>>> curRow = 1                                                              
>>> curCol = 2                                                            
>>> type(curRow)                                                       
type 'int'                                                            
>>> cur.execute("select COUNT(*) from adjacency where r = %d and c = %d", (curRow, curCol))                                     
Traceback (most recent call last):                                                 
    File "<stdin>", line 1, in <module>                                                     
    File "build/bdist.macosx-10.8-intel/egg/MySQLdb/cursors.py", line 183, in execute                                          
TypeError: %d format: a number is required, not str 

rc在表adjacency

兩個int領域,我作爲curRow也很困惑curCol顯然是int類型,而%d表示給我一個int。什麼是python作爲一個字符串混淆?

回答

0

因爲.execute()不只是做一個%替換您傳遞它的參數。它首先通過轉義來運行它們,在此過程中將值轉換爲字符串。

改爲使用%s

+0

你說什麼似乎工作。你能解釋一點嗎?在編程方面,這似乎並不簡單(我習慣Java)。這是否意味着一切都是一個字符串,我們永遠不必擔心它? – CodeKingPlusPlus

+0

'MySQLdb'預先運行您通過SQL轉義函數爲替換提供的每個值,以幫助防止[SQL注入](http://en.wikipedia.org/wiki/SQL_injection)。這樣做的一個副產品是轉義函數總是返回字符串,所以代入查詢文本的值總是一個字符串,而不管傳入的是什麼。 – Amber