pythondatabasepostgresqlflaskpg8000

python flask cursors.execute() of INSERT and DELETE doesn't work


I'm new to python development and I am trying to update a database with the following function, but sadly it doesn't work:

def db_update_favourite(user_id, id_layer,favourite):
    connection = g.db
    cursor = connection.cursor()
    cursor.execute(SCHEMA)
    chiave="favourite_layers";

    if(favourite):
        query = ("""INSERT INTO users_properties (id_user,chiave,index,val_bigint)
                VALUES(%s,%s,(SELECT max(index)+1 from users_properties),%s)
            """)
    else:
        query = ("""DELETE FROM users_properties
                WHERE  id_user=%s AND chiave=%s AND val_bigint=%s
            """)


    print query %(user_id,chiave,id_layer)
    try:
        res= cursor.execute(query, (user_id,chiave,id_layer))
    except Exception as e:
        print e
    print res
    print cursor.rowcount
    return cursor.rowcount>=1

If I go and check the database I see that this function didn't change the database at all.

If instead, I try the two queries manually with psql they work as expected.

As you can see I tried to debug but res is None, the Exception is not triggered and rowcount is always 1.

There are other methods that perform similar queries and they all work, What can it be? Any other ideas on How to further debug it, otherwise?

P.s I'm using pg8000 because the server is not mine and the code that was already existing use that library.


Solution

  • Use connection.commit() or g.db.commit() before you close the connection.