Jay Gattuso
Jay Gattuso

Reputation: 4130

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?

Upvotes: 8

Views: 9648

Answers (1)

dani herrera
dani herrera

Reputation: 51665

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."

Upvotes: 18

Related Questions