4

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?

2 Answers 2

13

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

Sign up to request clarification or add additional context in comments.

1 Comment

where I have to put conn.autocommit()? @JoeMornin @Henry
6

you need to commit:

conn.commit()

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

1 Comment

Thanks! I have been hunting all over looking for a fix and this was it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.