简体   繁体   中英

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

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?

您需要设置conn.autocommit() ,或者您需要执行conn.commit() - 请参阅常见问题解答

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM