2

I did a profiling of my python program and noticed that they were a lot of calls to commit and they took a lot of time.

Is it better performance wise to do :

db = MySQLcb.connect(...)
c = db.cursor(...)
c.execute('INSERT...)
c.commit()
c.execute('INSERT...)
c.commit()

or

db = MySQLcb.connect(...)
c = db.cursor(...)
c.execute('INSERT...)
c.execute('INSERT...)
c.commit()

Knowing that I am making a lot of inserts (thousands).

1
  • In MySQLdb, you can use autocommit=True in connect(). And for many inserts into same table, look into executemany. Commented Mar 7, 2018 at 18:39

1 Answer 1

1

As long as you are using InnoDB tables you might find the advice on this page useful.

Most databases have facilities for bulk insert, and MySQL is no exception.

If you find your insertions slow, make sure that you don't have autocommit set, as this forces a transaction around each individual operation.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for the link, it is really helpful ! But by question remains, do I need to do a db.commit after every c.executemany(...) I am doing ? Or is one at the end enough ?
@flyingdutchman ... your code above does not use executemany() which you only have to call once on a list of values.
@Parfait Yes I know, but it is not the point here, I am trying to ask if I need to do a manual commit after each execute or executemany()
@flyingdutchman ... See my comment above where you can set autocommit.
I do know that you can commit after each execute/executemany but you don't have to. You could, however, experience performance issues if you do this in an unthinking way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.