Python中的MySQL语句:变量不起作用

时间:2011-08-31 06:20:30

标签: python mysql mysql-python

当我尝试INSERT多个变量时,我遇到了MySQL和Python的MySQLdb问题。

我有一个包含三个字段的表格。第一个是auto_increment 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")

我还尝试了在语句周围使用tripple ticks,带有和不带括号的变量,没有字段名称和包含的第一个id字段。我也试过C-style-printf-stuff%(这不聪明!)。没有任何效果。

而你,在stackoverflow上光荣的人,你是我最后的希望:)。

FreeBSD 8.2上的MySQL-Server是5.5.9。 OSX Lion上的Python版本是2.7:82508

提前致谢!

斯特芬

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

2 个答案:

答案 0 :(得分:0)

关于您的更新:

AFAIK: fetchall()返回一个元组里面的元组。里面的那些元组是你从fetchone()得到的。您可以像

一样对其进行成像
fetchall() = (fetchone(), fetchtwo(), ...)

fetchone也返回一个具有实际变量值的元组。这就是为什么你不能简单地插入fetchall()的返回值。

只是为了澄清:你粘贴的插入语句,当你填写max_price的值时看起来像这样:

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

所以第一个%s被替换为元组(5)的第一个元素。您的insert语句如下所示:

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

我无法说清楚。

答案 1 :(得分: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')