mysql - 數(shù)據(jù)庫(kù)插入頻繁導(dǎo)致數(shù)據(jù)丟失
問(wèn)題描述
插入語(yǔ)句有兩條,循環(huán)插入這兩條只是簡(jiǎn)單寫(xiě)了下插入語(yǔ)句,沒(méi)有捕捉到異常
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ù)庫(kù)時(shí),發(fā)現(xiàn)少了很多,我猜應(yīng)該是頻繁插入導(dǎo)致數(shù)據(jù)丟失的,因?yàn)槲以诓迦霐?shù)據(jù)庫(kù)之前把數(shù)據(jù)print了一下,沒(méi)少。怎么解決這個(gè)問(wèn)題?
問(wèn)題解答
回答1:你是不是一次性循環(huán)了很多次啊如果我沒(méi)記錯(cuò)的話。數(shù)據(jù)庫(kù)有個(gè)隊(duì)列緩存的,如果一下子塞入太多數(shù)據(jù)占滿了緩存,就會(huì)產(chǎn)生丟失的現(xiàn)象如果有大量數(shù)據(jù)要插入的話,就要自己實(shí)現(xiàn)隊(duì)列,然后定時(shí)插入
或者試試事務(wù)
回答2:由于看不懂python語(yǔ)法,僅從sql的角度來(lái)提供2種解決方法:1、用事務(wù)的方式去進(jìn)行寫(xiě)入數(shù)據(jù),每1000條數(shù)據(jù)提交一次,例如:
fake code
for data.size BEGINfor 1000 INSERT INTO ...end COMMITend
2、將sql改成批量寫(xiě)入,性能有不少提高
INSERT INTO (...)VALUES (...),(...),(...),(...);回答3:
可以看下數(shù)據(jù)庫(kù)日志,看下執(zhí)行記錄。
回答4:你雖然代碼里面寫(xiě)了insert之后,commit。但是在什么時(shí)候提交,是在你的項(xiàng)目中的事務(wù)中控制的,而不是你在這里控制的,項(xiàng)目中可能從切面做了事務(wù)的控制。解決方案:1.分頁(yè)插,配置事務(wù),不要一次性插入,分批插入,分批commit數(shù)據(jù)。
相關(guān)文章:
1. 查詢mysql數(shù)據(jù)庫(kù)中指定表指定日期的數(shù)據(jù)?有詳細(xì)2. mysql - 怎么生成這個(gè)sql表?3. mysql儲(chǔ)存json錯(cuò)誤4. php - 公眾號(hào)文章底部的小程序二維碼如何統(tǒng)計(jì)?5. mysql - 表名稱前綴到底有啥用?6. mysql - 數(shù)據(jù)庫(kù)表中,兩個(gè)表互為外鍵參考如何解決7. Navicat for mysql 中以json格式儲(chǔ)存的數(shù)據(jù)存在大量反斜杠,如何去除?8. 在mybatis使用mysql的ON DUPLICATE KEY UPDATE語(yǔ)法實(shí)現(xiàn)存在即更新應(yīng)該使用哪個(gè)標(biāo)簽?9. mysql - 數(shù)據(jù)庫(kù)建字段,默認(rèn)值空和empty string有什么區(qū)別 11010. sql語(yǔ)句 - 如何在mysql中批量添加用戶?
