17

ubuntu version: 12.10
mysql server version: 5.5.29-0
python version: 2.7

I am trying to use MySQLdb to insert data into my localhost mysql server. I don't get any errors when I run the script but the data isn't enter into my table. I view tables with phpmyadmin.

I tried going back to basics and following a tutorial but same result. The weird thing is that I can create and delete tables but not enter data.

The code is from the tutorial even reports that 4 rows were inserted. What is preventing data from being entered into the table when the script reports everything is fine??

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 "%d rows were inserted" % cursor.rowcount 
BubbleGuppies
  • 5,750
  • 7
  • 20
  • 15
  • 1
    Is it possible that the cursor is wrapped in a transaction? – AndrewP Feb 18 '13 at 04:07
  • I am not sure but did you forget to add `;` at the end of the insert statement? – Srinivas Reddy Thatiparthy Feb 18 '13 at 04:09
  • AndrewP: I don't know what that means. Darklord: I added the semicolon and nothing changed. I get no error and even wrapped the code in a try/except statement with no failure. I'm thinking it is not the code but rather something wonky with the configuration. I'll keep trying, or maybe give up and try the Oracle library. – BubbleGuppies Feb 19 '13 at 00:16

1 Answers1

59

Add :

conn.commit()

at the bottom of your script.

On a side note, have a look at the following : http://mysql-python.sourceforge.net/MySQLdb.html

Ketouem
  • 3,820
  • 1
  • 19
  • 29
  • Specified library is quite outdated and there is an actively maintained fork it. Source code https://github.com/PyMySQL/mysqlclient, documentation https://mysqlclient.readthedocs.io/. – jbmeerkat Mar 15 '21 at 16:06