Why doesn't the 'insert' function add rows using MySQLdb?

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

I follow the code here in particular:

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 modify this code to create or delete tables, but I cannot get it to actually perform an INSERT . It returns the value of row.count , as expected (even when I change the value in the table, it changes to what I expect).

Every time I browse the database using PHPMyAdmin, no inserts are created. How to pass INSERT to the database?

+6
source share
1 answer

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

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

Quote Writing MySQL scripts using the Python DB-API :

"The commit method of the commit () object makes any unresolved changes in the current transaction to make them permanent in the database. In the DB-API, connections start with autosave disabled, so you must call commit () before disconnecting or changes may be lost. "

+15
source

Source: https://habr.com/ru/post/907829/


All Articles