Question

I'm creating a few different scripts that all interact with a central MySQL database to share data but I'm finding that some changes I make to the database wont propagate through or be readable to certain scripts until the database connection has been closed and re opened.

For example using the following code read_script will only print items that have been added to the database using write_scriptafter I quit and restart write_script. I'm new to MySQL so I'm not sure if there is a problem in my SQL or my python

read_script

connection = MySQLdb.connect(...)
while True:
    cur = connection.cursor()
    cur.execute("SELECT * FROM my_table")
    print cur.fetchall()
    cur.close()

write_script

connection = MySQLdb.connect(...)
cur = connection.cursor()
cur.execute("INSERT INTO my_table VALUES(some_data)")
cur.close()
connection.commit()

What do I need to do to ensure I get up to data data from the database?

Was it helpful?

Solution

Default transaction isolation is REPEATABLE READ. This means that your read_script will always read and show the same data. Put commit in your while-loop. Side note: Probably good to temporise reading using time.sleep(1).

OTHER TIPS

Yes, it looks like the assumption is that you are only going to perform a single transaction and then disconnect. If you have a different need, then you need to work around this assumption. You can put in a commit (though I would use a rollback if you are not actually changing data). Or you can change the isolation level on the cursor as mentioned by @geertjanvdk - from this discussion I used this:

dbcursor.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED")

Or, it looks like you can set auto commit to true on the connection:

dbconn.autocommit(True)

Though, again, this is not recommended if actually making changes in the connection.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top