Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't execute an INSERT statement in a Python script via MySQLdb

Tags:

python

sql

mysql

I'm trying to execute a basic INSERT statement on 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 the query from a Python script, no rows get inserted. Here's 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, this will print "Number of rows inserted: 1." I can also confirm that this query increments the ID field, because when I add another row via the command line, the value of its ID is the same as if the Python script had successfully inserted its rows. However, running a SELECT query returns none of the rows from the script.

Any idea what's going wrong?

like image 918
Joe Mornin Avatar asked Dec 02 '22 02:12

Joe Mornin


2 Answers

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

like image 71
Henry Avatar answered Dec 05 '22 01:12

Henry


you need to commit:

conn.commit()

http://mysql-python.sourceforge.net/FAQ.html#my-data-disappeared-or-won-t-go-away

like image 33
dting Avatar answered Dec 05 '22 02:12

dting