3

I'm having trouble with MySQL or Python and can't seem to isolate the problem. INSERTs only seem to last the run of the script and are not stored in the database.

I have this script:

import MySQLdb
db = MySQLdb.connect(host="localhost", user="user", passwd="password", db="example")
dbcursor = db.cursor()

dbcursor.execute("select * from tablename")
temp = dbcursor.fetchall()
print 'before: '+str(temp)

dbcursor.execute('INSERT INTO tablename (data1, data2, data3) VALUES ("1", "a", "b")')

dbcursor.execute("select * from tablename")
temp = dbcursor.fetchall()
print 'after: '+str(temp)

The first time I run it I get the expected output:

>>> 
before: ()
after: ((1L, 'a', 'b'),)

The problem is that if I run it again, the before comes out empty when it should already have the entry in it and the after doesn't break (data 1 is primary key).

>>> 
before: ()
after: ((1L, 'a', 'b'),)
>>> 
before: ()
after: ((1L, 'a', 'b'),)
>>> 
before: ()
after: ((1L, 'a', 'b'),)

If I try running the insert command twice in the same script it will break ("Duplicate entry for PRIMARY KEY")

Any idea what might be happening here?

3 Answers 3

10

You are not committing the transaction.

conn = MySQLdb.connect (host = "localhost",
                        user = "testuser",
                        passwd = "testpass",
                        db = "test")
cursor = conn.cursor()

cursor.execute(...)
conn.commit()

Reference

Sign up to request clarification or add additional context in comments.

2 Comments

If it isn't in the DB, why does the second select return that value? Is this the difference between transactional and non-transactional DBs?
@joaoc The second select returns the value because the result of the INSERT is visible to your own session, but not visible for others until you commit it
3

I think you need to call

db.commit()

1 Comment

After every dbcursor.execute or only once at the end?
2

The problem is you are not committing the changes. it can be done by conn.commit()

read more on this here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.