Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does: "Cannot commit when autoCommit is enabled” error mean?

In my program, I’ve got several threads in pool that each try to write to the DB. The number of threads created is dynamic. When the number of threads created is only one, all works fine. However, when there are multi-thread executing, I get the error:

org.apache.ddlutils.DatabaseOperationException: org.postgresql.util.PSQLException: Cannot commit when autoCommit is enabled.

I’m guessing, perhaps since each thread executes in parallel, two threads are trying to write at the same time and giving this error.

Do you think this is the case, if not, what could be causing this error?

Otherwise, if what I said is the problem, what I can do to fix it?

like image 593
Larry Avatar asked Aug 02 '11 16:08

Larry


People also ask

How do I turn on auto commit?

SET AUTOCOMMIT sets the autocommit behavior of the current database session. By default, embedded SQL programs are not in autocommit mode, so COMMIT needs to be issued explicitly when desired. This command can change the session to autocommit mode, where each individual statement is committed implicitly.

How do I enable autocommit in MySQL?

By default, autocommit mode is enabled in MySQL. Now, SET autocommit=0; will begin a transaction, SET autocommit=1; will implicitly commit. It is possible to COMMIT; as well as ROLLBACK; , in both of which cases autocommit is still set to 0 afterwards (and a new transaction is implicitly started).

How do you check autocommit is on or off?

To tell if AUTOCOMMIT is on or off, issue the set command: $ \set ... AUTOCOMMIT = 'off' ...

What happens when autocommit is off?

When auto-commit is disabled, you use a Connection object's commit and rollback methods to commit or roll back a transaction. The commit method makes permanent the changes resulting from the transaction and releases locks. The rollback method undoes all the changes resulting from the transaction and releases locks.


1 Answers

In your jdbc code, you should turn off autocommit as soon as you fetch the connection. Something like this:

DataSource datasource = getDatasource(); // fetch your datasource somehow
Connection c = null;
try{
  c = datasource.getConnection();
  c.setAutoCommit(false);
like image 52
Femi Avatar answered Sep 21 '22 04:09

Femi