SQLite3: How to know transaction is already started

You can use get_autocommit() to know transaction is already started or not.

  • When transaction is started: This function return 0 because auto-commit is disabled.
  • When transaction is not started: This function return non-0 because auto-commit is enabled. www.sqlite.org

Example

The error occurred if you start new transaction despite of already transaction is started. So you have to check transaction is already started by caller function before start new transaction in the current function.

void example(sqlite3* db) {
  char* err = NULL;
  bool transactionStarted = sqlite3_get_autocommit(db) == 0;

  if(!transactionStarted) {
    sqlite3_exec(db, "BEGIN TRANSACTION;", NULL, NULL, &err);
  }

  try {
    //  ... update records in the SQLite3 database

    if(!transactionStarted) {
      sqlite3_exec(db, "COMMIT;", NULL, NULL, &err);
    }
  }
  catch(const std::exception& e) {
    if(!transactionStarted) {
      sqlite3_exec(db, "ROLLBACK;", NULL, NULL, &err);
    }    
    throw;
  }
}

*This code omit error check.