python MySQLdb编写了select语句

Cod*_*lus 0 python select prepared-statement mysql-python

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

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

r并且c是表中的整数字段,adjacency并且还形成复合主键.curRow并且curCol是我的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") 
Run Code Online (Sandbox Code Playgroud)

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

  1. 我准备好的陈述有什么问题?

非常感谢所有帮助!

Aya*_*Aya 6

看起来你只是在错误的地方有一个支架.

更改...

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

...至...

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

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

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

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