2017-10-14 59 views
0

我遇到了MySQL問題,因爲在插入數萬條記錄時,我經常會遇到「數據庫有太多連接錯誤」。我正在使用Python和Scrapy來抓取網頁並將信息插入到MySQL中。下面是代碼:在插入成千上萬的記錄時防止MySql中的連接太多

import MySQLdb  

# connect to the MySQL server 
self.CONN = MySQLdb.connect(host=SQL_HOST, 
    user=SQL_USER, 
    passwd=SQL_PASSWD, 
    db=SQL_DB, 
    charset='utf8', use_unicode=True) 

cursor = self.CONN.cursor() 

sql = "INSERT INTO myTable (id, license, address, name, city, state, zip_code, country) \ 
      SELECT uuid(), '" + item['license_num'] + "', '" + item['address'] + "', '" + item['name'] + "', '" + item['city']+ "', '" + item['state'] + "', '" + item['city'] + "', '" + item['state'] + "', '" + item['zip_code'] + "', '" + item['country'] FROM (SELECT 1) t \ 
      WHERE NOT EXISTS (SELECT name FROM myTable WHERE license='" + item['license_num'] + "');" 

if cursor.execute(sql): 
    results = cursor.fetchall() 
    print results 
    print 'ADDED BUSINESS: ' + item['name'] 
    print json.dumps(dict(item), indent=4, sort_keys=True) 
    self.CONN.commit() 
    cursor.close() 

我想這可能是內存的問題,但我查了一下:

[[email protected] ~]# free -m 
      total  used  free  shared buffers  cached 
Mem:   4096  1896  2199  106   0  1370 
-/+ buffers/cache:  525  3570 
Swap:   0   0   0 

似乎並沒有成爲一個記憶的問題。我的磁盤空間中只有6%被使用。我不想重新啓動MySQL,因爲它可能會破壞我的數據。我希望如果我讓它運行,它會恢復。所以我的問題是如何提高下面的sql以防止太多的連接?

+0

結束MySQL連接你在做一個循環地方? –

+0

是的,每次Scrapy項目被刮掉時,都會調用該代碼。 – MoreScratch

+1

您是否正在創建與mysql有連接的太多對象?關閉遊標不會關閉與mysql的連接。理想情況下,您應該只有一個對象在過程中連接到MySQL數據庫。如果您在Linux下運行該進程,則可以使用「lsof」命令來檢查進程中打開的套接字或連接的數量。 –

回答

0

您必須確保每次調用代碼時都關閉光標。 這個代碼可以幫助

import MySQLdb  

# connect to the MySQL server 
self.CONN = MySQLdb.connect(host=SQL_HOST, 
    user=SQL_USER, 
    passwd=SQL_PASSWD, 
    db=SQL_DB, 
    charset='utf8', use_unicode=True) 

cursor = self.CONN.cursor() 

sql = """\ 
INSERT INTO myTable (id, license, address, name, city, state, zip_code, country) \ 
SELECT uuid(), \ 
'" + item['license_num'] + "', \ 
'" + item['address'] + "', \ 
'" + item['name'] + "', \ 
'" + item['city']+ "', \ 
'" + item['state'] + "', \ 
'" + item['city'] + "', \ 
'" + item['state'] + "', \ 
'" + item['zip_code'] + "', \ 
'" + item['country'] \ 
FROM (SELECT 1) t WHERE NOT EXISTS (SELECT name FROM myTable WHERE license='" + item['license_num'] + "'); 
""" 

try: 
    cursor.execute(sql): 
    results = cursor.fetchall() 
    print results 
    print 'ADDED BUSINESS: ' + item['name'] 
    print json.dumps(dict(item), indent=4, sort_keys=True) 
    self.CONN.commit() 
except Exception as e: 
    print str(e) 
finally: 
    cursor.close() 
+0

好吧,所以當我像你建議的那樣實現它時,我會得到「命令不同步;您現在無法運行此命令「(2014)異常 – MoreScratch

+0

是否應該爲每個插入打開一個新連接? – MoreScratch

0

嘗試關閉腳本

finally: 
    cursor.close() 
    self.CONN.close() # close connection