1

I am wondering why I am receiving this error:

cmd = "INSERT INTO resulttest (category, value, timestamp) VALUES (" + key + ", " + str(value) + ", " + str(timestamp) + ")"
c.execute(cmd)
db.commit()

    INSERT INTO resulttest (category, value, timestamp) VALUES (composed, 2, 1343186948.8)

Traceback (most recent call last):
  File "C:/Behavioral Technology/Google Drive/twitterthingv5test.py", line 94, in <module>
    moodParser()
  File "C:/Behavioral Technology/Google Drive/twitterthingv5test.py", line 92, in moodParser
    query()
  File "C:/Behavioral Technology/Google Drive/twitterthingv5test.py", line 37, in query
    main(columns)
  File "C:/Behavioral Technology/Google Drive/twitterthingv5test.py", line 81, in main
    c.execute(cmd)
  File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 174, in execute
    self.errorhandler(self, exc, value)
  File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
    raise errorclass, errorvalue

I believe it has something to do with how I am passing my values to the SQL command.

4

2 回答 2

4

您创建查询的代码没有尝试引用字符串值:

cmd = "INSERT INTO resulttest (category, value, timestamp) VALUES (" + key + ", " + str(value) + ", " + str(timestamp) + ")"

查看您打印的 SQL 语句:

INSERT INTO resulttest (category, value, timestamp) VALUES (composed, 2, 1343186948.8)

不应该引用“类别”吗?

首先,您不应该使用字符串操作来编写 SQL 语句。这就是 SQL 注入漏洞发生的方式。相反,您应该使用占位符并让 MySQL 库处理它们:

c.execute(
    "INSERT INTO resulttest (category, value, timestamp) VALUES (?, ?, ?)", 
    (key, value, timestamp)
)
于 2012-07-25T03:35:44.303 回答
0

如果 Ned Batchelder 的建议不起作用,这里有一个替代方案:

sql = "INSERT into resulttest (category, value, timestamp) VALUES (%s, %s, %s)"
c.execute(sql % (key, value, timestamp))

我遇到了一个问题,我的 SQL 命令没有被执行,遵循这种语法使它工作。

虽然你必须小心,因为使用%而不是,打开了 SQL 注入的可能性,但这是唯一对我有用的语法。可能是 Python-MySQL 版本和兼容性问题。

一个更好的主意是安装兼容版本并遵循正确的语法。

于 2012-07-27T10:58:44.233 回答