2014-04-19 60 views
1

我有一個大的json文件(+ - 50mb),我必須迭代,處理一些文本,然後將處理後的文本插入到mysql表中。從列表交互中插入數據的最佳方式

我的疑問是:

它會更好的記錄表中​​插入記錄,同時遍歷JSON文件。

move one item in json -> extract info I need -> open db connection -> insert record -> close db connection -> move to next item in json file... and so on until end of file 

在這種情況下,每次打開和關閉數據庫連接還是保持打開直到json文件結束會更好?

或者我認爲其他選項是迭代json文件並創建一個字典列表(每個記錄有一個字典,其中鍵爲插入字段,鍵的值爲值插入數據庫中),然後插入數據庫。

iterate over json file -> extract info I need -> store info in dictionary -> add dictionary to a list -> repeat until the end of the file -> open db connection -> iterate over list -> insert record 

在此情況下,纔有可能插入在數據庫中的整個列表一次,而不是遍歷目錄與一個記錄爲......我......插入記錄?

什麼是最好的選擇的任何想法?

很抱歉,如果這個問題可能看起來愚蠢的,但我是一個初學者,到處都找不到這個答案...我有超過10萬的記錄插入...

在此先感謝您的幫助!

回答

0

將所有記錄一次插入數據庫肯定會好得多:創建和關閉連接以及執行多個INSERT語句而不是一個INSERT語句的開銷相當大。如果MySQL扼流圈嘗試添加例如數據塊,那麼可能有100000條記錄需要一次性插入。 1000個記錄一氣呵成。

我假設內存使用不會是一個問題;這當然取決於每個記錄的大小。

如果您經常需要從python訪問數據庫,我的建議是使用sqlalchemy來訪問數據庫。絕對值得投資!使用sqlalchemy,代碼將如下所示:

CHUNKSIZE = 1000 

< parse JSON > 
< store into a list of dictionaries 'records' > 

< Refer to sqlalchemy tutorial for how to create Base and Session classes > 

class MyRecord(Base): 
    ''' SQLAlchemy record definition. 
     Let the column names correspond to the keys in the record dictionaries 
    ''' 
    ... 

session = Session() 
for chunk in [records[CHUNKSIZE*i:CHUNKSIZE*(i+1)] for i in range(1+len(records)/CHUNKSIZE): 
    for rec in chunk: 
    session.add(MyRecord(**rec)) 
    session.commit() 
+0

好的,謝謝!會看看它! – user2950162

相關問題