python MySQLdb编写了select语句

时间:2013-06-22 20:47:44

标签: python select prepared-statement mysql-python

在使用MySQLdb的python中我试图执行以下操作:

cur.execute("select COUNT(*) from adjacency where r = %d and c = %d)" % (curRow, curCol) 

rc是表adjacency中的整数字段,也是复合主键。 curRowcurCol是我的python程序中的整数变量。 MySQL抱怨道:

_mysql_exceptions.ProgrammingError: (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 '%d and c = %d' at line 1") 

最后,我想检查是否已存在与r=curCowc=curCol相邻的行。如果是,则更新表中的字段。否则在表格中插入一行。

  1. 我准备好的陈述有什么问题?
  2. 非常感谢所有帮助!

1 个答案:

答案 0 :(得分:6)

看起来你的支架位置错误。

更改...

cur.execute("select COUNT(*) from adjacency where r = %d and c = %d)" % (curRow, curCol)

...到...

cur.execute("select COUNT(*) from adjacency where r = %d and c = %d" % (curRow, curCol))

......虽然使用起来更安全......

cur.execute("select COUNT(*) from adjacency where r = %s and c = %s", (curRow, curCol))

...这将保护您免受潜在的SQL注入。