Unable to execute INSERT statement in Python script via MySQLdb

I am trying to execute a basic INSERT in a MySQL table from a Python script using MySQLdb. My table looks like this:

 CREATE TABLE `testtable` ( `id` int(11) NOT NULL AUTO_INCREMENT, `testfield` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) 

Running this query from the MySQL command line works fine:

 INSERT INTO `testtable` (`id`, `testfield`) VALUES (NULL, 'testvalue'); 

But when I try to execute a request from a Python script, the rows will not be inserted. Here is my code:

 conn = MySQLdb.connect(host=db_host, port=db_port, user=db_user, passwd=db_password, db=db_database) cursor = conn.cursor () cursor.execute ("INSERT INTO `testtable` (`id`, `testfield`) VALUES (NULL, 'testvalue')") print "Number of rows inserted: %d" % cursor.rowcount cursor.close() conn.close() 

Oddly enough, this will print "Number of rows inserted: 1." I can also confirm that this request increases the identifier field, because when I add another line through the command line, the value of its identifier is the same as if the Python script successfully inserted its lines. However, executing a SELECT query does not return any of the lines from the script.

Any idea what goes wrong?

+4
source share
2 answers

You either need to install conn.autocommit() , or you need to do conn.commit() - see the FAQ

+10
source

All Articles