国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

mysql - 數據庫插入頻繁導致數據丟失

瀏覽:128日期:2022-06-20 08:54:51

問題描述

插入語句有兩條,循環插入這兩條只是簡單寫了下插入語句,沒有捕捉到異常

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)

查看數據庫時,發現少了很多,我猜應該是頻繁插入導致數據丟失的,因為我在插入數據庫之前把數據print了一下,沒少。怎么解決這個問題?

問題解答

回答1:

你是不是一次性循環了很多次啊如果我沒記錯的話。數據庫有個隊列緩存的,如果一下子塞入太多數據占滿了緩存,就會產生丟失的現象如果有大量數據要插入的話,就要自己實現隊列,然后定時插入

或者試試事務

回答2:

由于看不懂python語法,僅從sql的角度來提供2種解決方法:1、用事務的方式去進行寫入數據,每1000條數據提交一次,例如:

fake code

for data.size BEGINfor 1000 INSERT INTO ...end COMMITend

2、將sql改成批量寫入,性能有不少提高

INSERT INTO (...)VALUES (...),(...),(...),(...);回答3:

可以看下數據庫日志,看下執行記錄。

回答4:

你雖然代碼里面寫了insert之后,commit。但是在什么時候提交,是在你的項目中的事務中控制的,而不是你在這里控制的,項目中可能從切面做了事務的控制。解決方案:1.分頁插,配置事務,不要一次性插入,分批插入,分批commit數據。

相關文章:
主站蜘蛛池模板: 高邑县| 清河县| 贡山| 井陉县| 外汇| 武汉市| 云龙县| 定安县| 无棣县| 孟津县| 无为县| 阳东县| 濮阳市| 忻城县| 新邵县| 金寨县| 垫江县| 亳州市| 平塘县| 克什克腾旗| 平山县| 三亚市| 子洲县| 内丘县| 高尔夫| 泽普县| 长岭县| 吴桥县| 潮安县| 崇礼县| 金湖县| 巢湖市| 昆明市| 浠水县| 安远县| 桦南县| 东明县| 舞钢市| 蓝山县| 天门市| 深圳市|