无法通过MySQLdb在Python脚本中执行INSERT语句 [英] Can't execute an INSERT statement in a Python script via MySQLdb

查看:213
本文介绍了无法通过MySQLdb在Python脚本中执行INSERT语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用MySQLdb从Python脚本在MySQL表上执行基本的INSERT语句.我的桌子看起来像这样:

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`)
)

从MySQL命令行运行此查询可以正常工作:

Running this query from the MySQL command line works fine:

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

但是当我尝试从Python脚本执行查询时,没有任何行插入.这是我的代码:

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()

奇怪的是,这将显示插入的行数:1".我还可以确认此查询增加了ID字段,因为当我通过命令行添加另一行时,其ID的值与Python脚本已成功插入其行的值相同.但是,运行SELECT查询不会返回脚本中的任何行.

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.

知道发生了什么事吗?

推荐答案

您要么需要设置conn.autocommit(),要么需要执行conn.commit()-请参见

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

这篇关于无法通过MySQLdb在Python脚本中执行INSERT语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆