MySQL rows delete when program exits

I’m using Python and MySQLdb to add rows to my database. It seems that when my script exits, the rows get deleted. My last lines before the script exits do a “select *” on the table, which shows my one row. When I re-run the script, the first lines (after opening the connection) do the same “select *” and return zero results. I’m really at a loss here. I’ve been working for about 2 hours on this, and can’t understand what could be accessing my database.

Also, between running the scripts, I run the “select *” manually from a terminal with zero results.

If I manually add a row from the terminal, it seems to last.

The query to insert the row:

cursor.execute("INSERT INTO sessions(username, id, ip) VALUES (%s, %s, %s)", (username, SessionID, IP]))

The query I use to check the data:

cursor.execute("select * from sessions")
print cursor.fetchall()

This shows the row before the program exits, then shows nothing when the program is run again.

Thanks in advance for all the help.

Answer

Looks like you need to connection.commit() your changes after you execute the query (replace connection with your DB connection variable).

http://docs.python.org/library/sqlite3.html

Connection.commit(): This method commits the current transaction. If you don’t call this method, anything you did since the last call to commit() is not visible from other database connections. If you wonder why you don’t see the data you’ve written to the database, please check you didn’t forget to call this method.

Leave a Reply

Your email address will not be published. Required fields are marked *