2015-11-11 35 views
0

我想通過插入命令多個數據集插入到MySQL表。爲此,我定義如下方法:爲executemany「並非所有串格式化期間轉換參數」()

def addRecords(self, records): 
    """Add a list of shop -> filename entries into the records""" 
    import pprint 
    pprint.pprint(records) 
    self.cursor.executemany(""" 
     INSERT INTO foo_records ('shop_id', 'filename', 'missing_since', 'last_reported') 
     VALUES (?, ?, NOW(), NOW()) 
     """, records) 

當我執行此我得到TypeError: not all arguments converted during string formatting的排隊叫號executemany

'shop_id' 爲INT(11)在MySQL和 '文件名' 被定義爲VARCHAR(60)。

records的內容是這樣的:

[(1234, u'foo.csv'), 
(1234, u'bar.csv'), 
.. 
(1456, u'foobar.txt')] 

缺少什麼我在這裏?

編輯:我曾在SQL一個愚蠢的錯誤。列名被嵌入在'中。當我刪除它們時,它與%s而不是?

回答

0

我相信問題是問號。

self.cursor.executemany(""" 
     INSERT INTO foo_records ('shop_id', 'filename', 'missing_since', 'last_reported') 
     VALUES (%s, %s, NOW(), NOW()) 
     """, records) 

:如果你使用%s(如doc指定),而不是會發生什麼?

+0

爲此,我收到'_mysql_exceptions.ProgrammingError:(1064,「您的SQL語法錯誤;檢查對應於你的MySQL服務器版本使用附近的'shop_id」正確的語法手冊,‘文件名’ ,'missing_since','last_reported')\ n VALUES(437'in line 1「),因爲shop_id應該是一個整數,而不是一個字符串。但是,當我爲shop_id設置'%d'時,錯誤消息是'TypeError:%d格式:需要一個數字,而不是str'。我也試圖想出一個元組,其中shop_id被保存爲一個字符串。然後我也使用'%d'。這也不起作用。 –

+0

MySQL提供'轉換()'函數(https://dev.mysql.com/doc/refman/5.7/en/charset-convert.html)(例如'選擇轉換( '1AA',整數),CONVERT(」 0x120',INTEGER),CONVERT('10',INTEGER);')。您可以將它添加到插入以將您的值轉換爲整數。 –

相關問題