What is the return of an UPDATE query?

Question:

I’m using sqlalchemy (the ORM syntax) in combination with sqlite and the databases library and I’m trying to wrap my head around what that combination returns when doing update queries. I’m running a testcase and I have sqlalchemy set up to roll back upon execution of each testcase via force_rollback=True.

db = databases.Database(DB_URL, force_rollback=True)


query = update(my_table).where(my_table.columns.id == some_id_to_update).values(**values)
res = await db.execute(query)

When working with psql, I’d expect res to be the number of rows that were affected by the UPDATE query, but from reading the documentation, sqlite seems to behave differently in that it doesn’t return anything. I tested this manually by connecting to the database via sqlite3 and as expected, there is no return when doing UPDATE queries. sqlalchemy however does return something, which I assume is the number of total rows in the table, but I’m not sure. Can anybody shed some light into what is actually returned?

What’s more, when I tried to get the number of rows affected by the UPDATE query via SELECT changes(), I’m also getting the number of total rows in the table and not the rows affected by the most recent query. Do I have a misunderstanding of what changes() does?

Asked By: sobek

||

Answers:

"The changes() function returns the number of database rows that were changed or inserted or deleted by the most recently completed INSERT, DELETE, or UPDATE statement, exclusive of statements in lower-level triggers."

When you use the Python sqlite3 module, you use .executeXXX interfaces to evaluate/prepare your query. If the query is supposed to modify the database, it does it at this stage. You have to use the same interface to prepare a SELECT statement. In either case, the .executeXXX interfaces never return anything. To get the result of a SELECT query, you have to use a .fetchXXX interface after running .executeXXX.

To get the number of changed rows after INSERT, DELETE, or UPDATE statement via sqlite3, you can also take the difference in con.total_changes before/after running .executeXXX.

Answered By: PChemGuy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.