MySQL INSERT data not being saved in proper db but only temporarily?

I'm having problems with MySQL or Python and can't seem to isolate the issue. INSERT

it seems like it only lasts for the run script and is not saved to 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, it before

will exit empty if there is already a record in it, and then it is not interrupted (data 1 is the primary key).

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

      

If I try to run insert command twice in the same script, it breaks ("Duplicate entry for PRIMARY KEY")

Any idea what might be going on here?

+2


source to share


3 answers


You are not making a transaction.

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

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

      



Link

+9


source


I think you need to call



db.commit ()

+3


source


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

more about it here

+2


source







All Articles