0

我是 python 新手,我有一个无法解决的简单问题。我在 Windows 平台上,不幸的是我无法改变这个工作原因。我必须连接到许多 mysql 表并使用提取的数据做一些事情。我拥有的代码:

conn = mysql.connector.Connect(host='<ip>',user='<user>',\
       password='',database='<my database>')

c = conn.cursor()

c.execute ("select field from TABLE")

results = c.fetchall()


for row in results:
    c.execute("select * from otherTable where nodo = %s",(str(row[0])))
    if c.rowcount == 0:
        doSomething()
    else:
        doOtherThing()

c.close()

当我用 Python34 运行它时,我得到了错误:

“您的 sql 合成器有错误;请查看与您的 mysql 服务器版本相对应的手册,以在第 1 行的 '%s' 附近使用正确的合成器

谢谢

4

1 回答 1

0

你需要像这样在 %s 周围加上单引号:c.execute("select * from otherTable where nodo = '%s'",(str(row[0])))

您还应该考虑将查询放入变量中,然后像这样执行它:

query = ("select * from otherTable where nodo = '%s'",(str(row[0])))

c.execute(query)

这种方式有助于防止潜在的 sql 注入攻击,并允许您print(query)在遇到错误时调试 sql 语句。

于 2015-03-27T18:17:40.780 回答