Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the 'insert' function adding rows using MySQLdb?

I'm trying to figure out how to use the MySQLdb library in Python (I am novice at best for both of them).

I'm following the code here, specifically:

cursor = conn.cursor ()
cursor.execute ("DROP TABLE IF EXISTS animal")
cursor.execute ("""
   CREATE TABLE animal
   (
     name     CHAR(40),
     category CHAR(40)
   )
 """)
cursor.execute ("""
   INSERT INTO animal (name, category)
   VALUES
     ('snake', 'reptile'),
     ('frog', 'amphibian'),
     ('tuna', 'fish'),
     ('racoon', 'mammal')
 """)
print "Number of rows inserted: %d" % cursor.rowcount
cursor.close ()
conn.close ()

I can change this code to create or drop tables, but I can't get it to actually commit the INSERT. It returns the row.count value as expected (even when I change the value in the table, it changes to what I expect it to be).

Every time I look into the database with PHPMyAdmin there are no inserts made. How do I commit the INSERT to the database?

like image 298
Jay Gattuso Avatar asked Feb 07 '12 08:02

Jay Gattuso


1 Answers

You forget commit data changes, autocommit is disabled by default:

   cursor.close ()
   conn.commit ()
   conn.close ()

Quoting Writing MySQL Scripts with Python DB-API documentation:

"The connection object commit() method commits any outstanding changes in the current transaction to make them permanent in the database. In DB-API, connections begin with autocommit mode disabled, so you must call commit() before disconnecting or changes may be lost."

like image 58
dani herrera Avatar answered Nov 04 '22 20:11

dani herrera