def get_users ():
conn = sqlite3.connect ("crm.sqlite")
cursor = conn.cursor ()
sql = "SELECT * FROM customers"
results = cursor.execute (sql)
users = results.fetchall ()
conn.commit ()
conn.close ()
return users

There are things you may not know when using a database in Python.
I would like to know two points.

First, why is commit () necessary?

Second, what is commit () doing?
Is it the same as Git commit?
I can't imagine commit in the database.

Thanks for your answer.

  • Answer # 1

    Commit in the database means "confirm changes".
    * Same for git

    For example, if you consider transferring money between bank accounts

    Remit money from the sender account + reduce fees

    Add money to the destination account

    The two processes

    must be performed in order. 1. If you just did 1. and didn't do 2. It's hard, and if 1. succeeds but 2. fails (account number is wrong), you have to go back to not doing 1 ..
    Such a series of processes that cannot be divided can be collectively confirmed/destroyed collectively as a transaction in a database. commit is a "confirm transaction result". This is called rollback.

    Transactions are usually unnecessary (*) if they are just references, so commits are also unnecessary, but it is customary to perform a commit to indicate that a series of processing has been completed. (Depending on the database settings, a transaction may be started implicitly at the time of SELECT)
    * During the series of processes starting from the reference, a transaction may be performed to perform an exclusive process of "Do not tamper with the record from another"

  • Answer # 2

    COMMIT will delete the contents of DELETE, INSERT, and UPDATE. Save (confirm). You can cancel DELETE, INSERT and UPDATE contents by ROLLBACK before COMMIT.

    When transferring 10,000 yen from A's account to B's account,

    Execute UPDATE that deducts 10,000 yen from A's account balance,

    Execute an UPDATE that adds 10,000 yen to B's account balance,

    3. COMMIT.

    was successful, but

    If any error occurs in

    , ROLLBACK and start from 1.

    Commit is not required because the question code is only CONNECT and SELECT.