0

I have an module in my program that increments the no of logins(login_count) by 1 using textual SQL but on the same transaction, when I try to retrieve the no of logins using ORM, I still get the previous value.

stmt = "UPDATE user SET login_count = login_count + 1 WHERE userid = {}".format(id)
session.execute(stmt)
user = session.query(User).get(id)
print(user.login_count)

But when I change the query to Textual SQL, I am able to get the updated value. Does Textual SQL create a separate transaction?

stmt = "SELECT * FROM user WHERE userid = {}".format(id)
user = session.execute(stmt)
print(user.login_count)
  • did you `commit` your `session`? you need to `commit` to persist – Amin Taghikhani Oct 28 '21 at 08:21
  • I commit everything only once I'm done with all DB executions at the end. The weird thing is for new users, I insert a new record using the normal SQLAlchemy Core method then query and I get the updated result without committing. – Jude Diñoso Oct 28 '21 at 08:30
  • if you use a common session for queries it's work fine, but if session is different for queries you need to `commit` and `persist` the data. – Amin Taghikhani Oct 28 '21 at 08:39
  • Yeah I used the same session to update and query but if I try to query by ORM, it doesn't get the updated value but if I did it in CORE, I get the updated value. I am wondering because this only applies to update operations. For insert and delete, it's working fine. – Jude Diñoso Oct 28 '21 at 08:49
  • Related: https://stackoverflow.com/questions/19143345/about-refreshing-objects-in-sqlalchemy-session/19144652#19144652, https://stackoverflow.com/questions/56640429/using-session-query-to-read-uncommitted-data-in-sqlalchemy/ – Ilja Everilä Oct 28 '21 at 21:02

0 Answers0