I've been working on this for a while now and searches on the internet have not come up with a solution.
I want to check if another process is accessing my DB before accessing it. I have a table with columns id and state. If state is 1 then I want to change it to 0 and continue to access, otherwise I want to leave it alone. Below is my code, I can't see why it won't work BUT it hangs every time on the last line here cursor.execute(set_lock)
get_lock = "SELECT state FROM running WHERE id=1"
cursor.execute(get_lock)
result = cursor.fetchall()
if(result[0][0]):
set_lock = "UPDATE running SET state=0 WHERE id=1"
cursor.execute(set_lock)
I'm pretty sure it has something to do with the reuse of the cursor, but I can't see why it should be a problem, I've done it before successfully. Any help you be great.
Cheers
I thought I had the problem solved but the fix was flakey, it seemed to work to start with but then started returning the wrong state. Running the MySQL statement in PHPMyAdmin it returned 1 as it should, but when printing the result it returned 0 and so skipped the content of the if statement.
cursor.execute("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;")
get_lock = "SELECT state FROM running WHERE id=1;"
cursor.execute(get_lock)
result = cursor.fetchall()
if(result[0][0]):
set_lock = "UPDATE running SET state=0 WHERE id=1;" //Lock
cursor.execute(set_lock)
cursor.execute("COMMIT;")
---- DO WHAT I NEED TO DO ----
set_lock = "UPDATE running SET state=1 WHERE id=1;" //Unlock
cursor.execute(set_lock)
cursor.execute("COMMIT;")
cursor.execute("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;")
cursor.close()
Any ideas?