mysql - 數(shù)據(jù)庫插入頻繁導(dǎo)致數(shù)據(jù)丟失
問題描述
插入語句有兩條,循環(huán)插入這兩條只是簡單寫了下插入語句,沒有捕捉到異常
def process_item(self, item, spider):#print(item)try: with self.connection.cursor() as cursor:#Create a new recordsql1 = 'INSERT INTO staff (XNXQ, department, teacher, gender, title, note1, note2) VALUES (%s, %s, %s, %s, %s, %s, %s)'cursor.execute(sql1, (item[’first’][’XNXQ’], item[’first’][’department’], item[’first’][’teacher’], item[’first’][’gender’], item[’first’][’title’], item[’first’][’note1’], item[’first’][’note2’]))self.connection.commit()#Create a new recordcursor.execute('select max(id) from staff')teacherId = cursor.fetchone()[’max(id)’]print(’teacherId:’ + str(teacherId))print(item[’second’]) sql2 = 'INSERT INTO staffCourse (teacherId, snum, course, credit, teachWay, courseType, classNum, className, stuNum, week, section, location) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'cursor.execute(sql2, (teacherId, item[’second’][’snum’], item[’second’][’course’], item[’second’][’credit’], item[’second’][’teachWay’], item[’second’][’courseType’], item[’second’][’classNum’], item[’second’][’className’], item[’second’][’stuNum’], item[’second’][’week’], item[’second’][’section’], item[’second’][’location’]))self.connection.commit()except Exception as e: print(’------------------------------------------’) print(e)
查看數(shù)據(jù)庫時,發(fā)現(xiàn)少了很多,我猜應(yīng)該是頻繁插入導(dǎo)致數(shù)據(jù)丟失的,因為我在插入數(shù)據(jù)庫之前把數(shù)據(jù)print了一下,沒少。怎么解決這個問題?
問題解答
回答1:你是不是一次性循環(huán)了很多次啊如果我沒記錯的話。數(shù)據(jù)庫有個隊列緩存的,如果一下子塞入太多數(shù)據(jù)占滿了緩存,就會產(chǎn)生丟失的現(xiàn)象如果有大量數(shù)據(jù)要插入的話,就要自己實現(xiàn)隊列,然后定時插入
或者試試事務(wù)
回答2:由于看不懂python語法,僅從sql的角度來提供2種解決方法:1、用事務(wù)的方式去進(jìn)行寫入數(shù)據(jù),每1000條數(shù)據(jù)提交一次,例如:
fake code
for data.size BEGINfor 1000 INSERT INTO ...end COMMITend
2、將sql改成批量寫入,性能有不少提高
INSERT INTO (...)VALUES (...),(...),(...),(...);回答3:
可以看下數(shù)據(jù)庫日志,看下執(zhí)行記錄。
回答4:你雖然代碼里面寫了insert之后,commit。但是在什么時候提交,是在你的項目中的事務(wù)中控制的,而不是你在這里控制的,項目中可能從切面做了事務(wù)的控制。解決方案:1.分頁插,配置事務(wù),不要一次性插入,分批插入,分批commit數(shù)據(jù)。
相關(guān)文章:
1. 跟著課件一模一樣的操作使用tp6,出現(xiàn)了錯誤2. PHP類屬性聲明?3. angular.js - 這是什么錯?誰遇到過?給點提示4. transform - css3 translate 的水平垂直居中問題求解5. angular.js - angular里的ui-view里,獲取當(dāng)前頁面的狀態(tài)參數(shù)用$state.params,在vue里類似的語法是什么呢?6. javascript - 安裝了babel,不起作用7. vue.js - nginx怎么修改跨域配置?8. css - div外層有一圈白色9. node.js - 初次安裝vue-cli遇到的問題10. 前端 - 應(yīng)該先從angularJS , vue.js , react 這些框架中的哪個開始入手?
