10

The documentation for the Pandas function to_sql() available for DataFrame objects (see to_sql() documentation) does not state that a commit() call on the connection is needed (or recommended) to persist the update.

Can I safely assume that DataFrame.to_sql('table_name', con) will always automatically commit the changes (like in: con.commit())?

1

1 Answer 1

11

Yes, at the end of the day it will be commited automatically.

Pandas calls SQLAlchemy method executemany (for SQL Alchemy connections):

conn.executemany(self.insert_statement(), data_list)

And according to the SQL Alchemy docs executemany issues commit at the end.

For SQLite connection commit is called explicitly:

def run_transaction(self):
    cur = self.con.cursor()
    try:
        yield cur
        self.con.commit()
    except:
        self.con.rollback()
        raise
    finally:
        cur.close()
Sign up to request clarification or add additional context in comments.

5 Comments

The Pandas function to_sql() also works when SQLAlchemy is not installed, in which case it uses sqlite (if I understand the documentation correctly). Is the commit then also guaranteed?
I cannot (unambiguously) find the SQLite connections are deprecated in Pandas. There are some discussions about this (here and here), and my understanding is that SQLite connections (via sqlite3) are still a supported feature (possibly under the flag 'legacy').
@TomVerhoeff, yes, that's correct. Sorry for the missleading information. I've mixed it up with the deprecated flavor in to_sql
The links to the code lines are no longer applicable as they didn't refer to a specific git revision, so it's hard now to follow. It would be nice if we could control commit behavior explicitly through sqlalchemy api as an answer to this.
I think I don't see an explicit commit in github.com/pandas-dev/pandas/blob/… which is called by Pandas for this. It seems that the python API to sqlite does not auto-commit if I'm looking in the right place. On the other hand you can't create_engine(isolation_level="AUTOCOMMIT") for sqlite, so I'm not sure yet what is the default commit behavior with sqlite using sqlalchemy.

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.