mysql - 数据库插入频繁导致数据丢失
问题描述
插入语句有两条,循环插入这两条只是简单写了下插入语句,没有捕捉到异常
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数据。
相关文章:
1. javascript - 一排三个框,各个框的间距是15px,距离外面的白框间距也是15px,这个css怎么写?2. javascript - jQuery post()方法,里面的请求串可以转换为GBK编码么?可以的话怎样转换?3. html5 - vue-cli 装好了 新建项目的好了,找不到项目是怎么回事?4. django - python 2层文件夹导入5. python - 用urllib抓取网页上的下载链接,目标文件是xls形式,但发现抓下来的xls是空表,里面只有一句报错信息,求帮助。6. 用CSS3 box-sizing 属性实现两个并排的容器,如果想让容器中间有间隔该如何实现7. mysql - C#连接数据库时一直这一句出问题int i = cmd.ExecuteNonQuery();8. css - ul ol前边的标记如何调整样式呢9. javascript - vue 手机端项目在进入主页后 在进入子页面,直接按返回出现空白情况10. python3.x - python 中的maketrans在utf-8文件中该怎么使用

网公网安备