简体   繁体   English

在Java代码中频繁地提交插入数据库是否是一种好习惯?

[英]Is it a good practice to do frequently commits for insert to database in java code?

My java code reads the excel file and writes (insert) data from it to oracle database. 我的Java代码读取excel文件并将数据从其中写入(插入)到oracle数据库。

For example, I need to read some similar cells in 2000 rows of excel file, my code reads it, insert to database and after do commit. 例如,我需要在Excel文件的2000行中读取一些类似的单元格,我的代码将其读取,插入数据库并进行提交。

The first approximately 1000 rows inserts very fast, but another 1000 rows inserts very long. 前大约1000行插入速度非常快,而另外1000行插入的时间很长。

Possibly reason in the lack of memory. 可能是因为缺少记忆。

So, I think to do frequently commits while data is loading to database (eg do commit after every 50 rows read). 因此,我认为在数据加载到数据库时要频繁提交(例如,每读取50行就提交一次)。

Is it good practice to do it or there are other ways to solve this problem? 是这样做的好习惯,还是有其他方法可以解决此问题?

Commits are for atomic operations in the database. 提交用于数据库中的原子操作。 You don't just throw them around because you feel like it. 您不只是因为喜欢就扔它们。 Each transaction is generally (depending on isolation level, but assuming serial isolation) a distinct, all-or-nothing operation. 通常,每个事务都是(取决于隔离级别,但假设是串行隔离)一个独特的,全有或全无的操作。

If you don't know what is causing database transaction to take "long time", you should read the logs or talk to someone that knows how to diagnose the cause of the "slowdown" and remedies it. 如果您不知道是什么原因导致数据库事务花费“长时间”,则应阅读日志或与知道如何诊断“减速”原因并进行补救的人员交谈。 Most likely reason is bad configuration. 最可能的原因是配置错误。

The bottom line is, people have transactions that insert 100,000 or even millions of rows as a single transaction without causing issues. 最重要的是,人们在一次交易中插入了100,000甚至数百万行的交易而不会引起问题。 And generally, it is better not to commit often for performance reasons. 通常,出于性能原因,最好不要经常提交。

Databases always have to be consistent, ie only commit, if your data is consistent, even if your program crashes afterwards . 数据库始终必须保持一致,即即使您的程序随后崩溃,只要您的数据保持一致,也只需提交

(If you don't need that consistency, then why do you use a DB?) (如果您不需要这种一致性,那么为什么要使用数据库?)

PS: You won't go out of memory that fast. PS:您不会很快就耗尽内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM