Python中的MySQL语句:变量不工作

2 投票
2 回答
1816 浏览
提问于 2025-04-17 00:50

我在用MySQL和Python的MySQLdb时遇到了一个问题,特别是在尝试插入多个变量的时候。

我有一个叫做wordurl的表,这个表有三个字段。第一个字段是自动增长的ID,第二和第三个字段用来存放值。第二个和第三个字段分别叫做word_id和url_id。

这是我的代码。

cursor.execute("INSERT INTO wordurl (word_id, url_id) VALUES (%s, %s)", (word_temp_id, url_temp_id))

当我只插入一个值的时候,代码可以正常运行,但插入两个值就不行了。

错误信息是:

(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '),), (('2',),))' at line 1")

我还尝试过用三重引号包裹语句,变量有加括号和不加括号的情况,甚至不写字段名,或者把第一个ID字段也包含进去。我还试过用C风格的printf格式 %(这其实不太聪明!)。但是都没有成功。

而你们,StackOverflow上的各位,我的最后希望就是你们了 :)

我的MySQL服务器是5.5.9,运行在FreeBSD 8.2上。Python版本是2.7:82508,运行在OSX Lion上。

提前谢谢大家!

Steffen

更新:我使用cursor.fetchall()和cursor.fetchone()来获取ID。也许这个信息很重要。

2 个回答

0

你试过这个吗:

cursor.execute("INSERT INTO wordurl (word_id, url_id) VALUES ('%s', '%s')" %(word_temp_id, url_temp_id))

这要看你想插入什么变量,不过对于字符串来说,这是必要的。

注意一下区别:

>>> word_temp_id = "bla1"
>>> url_temp_id = "bla2"
>>> query = "INSERT INTO wordurl (word_id, url_id) VALUES (%s, %s)" %(word_temp_id, url_temp_id)
>>> print query
INSERT INTO wordurl (word_id, url_id) VALUES (bla1, bla2)
>>> query = "INSERT INTO wordurl (word_id, url_id) VALUES ('%s', '%s')" %(word_temp_id, url_temp_id)
>>> print query
INSERT INTO wordurl (word_id, url_id) VALUES ('bla1', 'bla2')
0

关于你的更新:

据我所知:

fetchall() 会返回一个包含多个元组的元组。里面的那些元组就是你从 fetchone() 得到的结果。你可以想象成这样:

fetchall() = (fetchone(), fetchtwo(), ...)

而 fetchone() 也会返回一个元组,里面包含了实际的变量值。这就是为什么你不能直接把 fetchall() 的返回值插入到数据库里的原因。

为了更清楚一点:你粘贴的插入语句,当你填入 max_price 的值时,看起来是这样的:

c.execute("""SELECT spam, eggs, sausage FROM breakfast WHERE price < %s""", (5,))

所以第一个 %s 会被元组中的第一个元素(5)替换。你的插入语句看起来是这样的:

cursor.execute("INSERT INTO wordurl (word_id, url_id) VALUES (%s, %s)", (((233L,),), ((3L,),)))

我想我已经说得很清楚了。

撰写回答