Search code examples
pythonsqliteapsw

Return rows changed on UPDATE sequence


I am trying to return what rows are used in my UPDATE sequence, to check if it actually updated anything or it tried updating a nonexistent row, but I am having trouble getting the actual rows returned

Upon asking friends and viewing other articles, I've tried using methods that they presented, like using sqlite3's rowcount method, as well as a RETURNING statement in the execute function, but both throw a AttributeError and SQLError, respectively.

def set_reason(guild: str, warn_id: int, reason):
    warns.execute("UPDATE warns SET reason=:reason WHERE id=:id AND server=:guild", {'reason': reason, 'id': warn_id, 'guild': guild})
    return warns.fetchone()

Trying to use the RETURNING statement:

warns.execute("UPDATE warns SET reason=:reason WHERE id=:id AND server=:guild RETURNING warns.*", {'reason': reason, 'id': warn_id, 'guild': guild})

I get apsw.SQLError: SQLError: near "RETURNING": syntax error.

And trying to use the rowcount method:

warns.execute("UPDATE warns SET reason=:reason WHERE id=:id AND server=:guild", {'reason': reason, 'id': warn_id, 'guild': guild}).rowcount()

I get 'AttributeError: 'apsw.Cursor' has no attribute 'rowcount'`


Solution

  • According to this APSW docs page, the changes() method is on the connection object, not the cursor object.

    See this answer for a direct SQL query to get the same info. Follow the link for more details about the function. In case it's not clear, you just execute SELECT changes() and retrieve the result like any other single-result query.