Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyMysql UPDATE query

I've been trying using PyMysql and so far everything i did worked (Select/insert) but when i try to update it just doesn't work, no errors no nothing, just doesn't do anything.

import pymysql
connection = pymysql.connect(...)
cursor = connection.cursor()
cursor.execute("UPDATE Users SET IsConnected='1' WHERE Username='test'")
cursor.close()
connection.close()

and yes I've double checked that Users, IsConnected and Username are all correct and test does exist (SELECT works on it)

what's my problem here?

like image 939
Shay Avatar asked Jul 20 '13 02:07

Shay


2 Answers

When you execute your update, MySQL is implicitly starting a transaction. You need to commit this transaction by calling connection.commit() after you execute your update to keep the transaction from automatically rolling back when you disconnect.

MySQL (at least when using the InnoDB engine for tables) supports transactions, which allow you to run a series of update/insert statements then have them either all commit at once effectively as a single operation, or rollback so that none are applied. If you do not explicitly commit a transaction, it will rollback automatically when you close your connection to the database.

like image 200
Joe Day Avatar answered Sep 20 '22 11:09

Joe Day


In fact, what @JoeDay has described above has little to do with default MySQL transaction's behaviour. MySQL by default operates in auto-commit mode and normally you don't need any additional twist to persist your changes:

By default, MySQL runs with autocommit mode enabled. This means that as soon as you execute a statement that updates (modifies) a table, MySQL stores the update on disk to make it permanent. The change cannot be rolled back.

PEP-249's (DB API) authors decided to complicate things and break Zen of Python by making a transaction's start implicit, by proposing auto-commit to be disabled by default.

What I suggest to do, is to restore MySQL's default behaviour. And use transactions explicitly, only when you need them.

import pymysql

connection = pymysql.connect(autocommit=True)

I've also written about it here with a few references.

like image 40
saaj Avatar answered Sep 19 '22 11:09

saaj