2009-06-10 108 views
5

我使用Python及其MySQLdb模塊將一些測量數據導入Mysql數據庫。我們擁有的數據量相當高(目前約爲250 MB的csv文件,還有更多內容)。Python + MySQLdb executemany

目前我使用cursor.execute(...)導入一些元數據。這不是問題,因爲這些只有少數條目。

的問題是,當我嘗試使用cursor.executemany()進口數量較多的實際測量數據,MySQLdb的提出了一個

TypeError: not all arguments converted during string formatting 

我當前的代碼是

def __insert_values(self, values): 
    cursor = self.connection.cursor() 
    cursor.executemany(""" 
     insert into values (ensg, value, sampleid) 
     values (%s, %s, %s)""", values) 
    cursor.close() 

哪裏values是每個包含三個字符串的元組列表。任何想法可能是這個錯誤?

編輯:

值由

yield (prefix + row['id'], row['value'], sample_id) 

生成,然後讀入一個列表千出現的同時,行和迭代器csv.DictReader到來。

+1

您是否驗證了值包含正確的數據? 另外,你應該看看使用LOAD LOCAL DATA INFILE。它可以快得多。 – 2009-06-10 10:36:38

+0

問題是數據需要進行預處理(目前在同一個python腳本中完成),並且創建此類大型數據集的冗餘副本不太可行。 這些值應該沒問題,因爲我使用調試器檢查了這些值。 – lhahne 2009-06-10 10:44:14

回答

7

回顧展這是一個非常愚蠢的埠很難發現錯誤。值是sql中的關鍵字,因此表名值需要引號。

def __insert_values(self, values): 
    cursor = self.connection.cursor() 
    cursor.executemany(""" 
     insert into `values` (ensg, value, sampleid) 
     values (%s, %s, %s)""", values) 
    cursor.close() 
3

您收到的消息表示在executemany()方法中,其中一個轉換失敗。檢查values列表比3

不再是一個元組快速驗證:

max(map(len, values)) 

如果結果高於3,找到你的壞元組過濾器:

[t for t in values if len(t) != 3] 

或者,如果你需要的索引:

[(i,t) for i,t in enumerate(values) if len(t) != 3]