我想在where子句中使用带变量的select语句。我已经对此进行了研究How to use variables in SQL statement in Python?和Inserting Variables MySQL Using Python, Not Working。香港专业教育学院尝试实施所提供的解决方案,但它无法正错误代码
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 '?' at line 1
下面是代码:
name = input("Write your name")
mycursor.execute("SELECT name FROM workers WHERE symbol=?", name)
我做错了什么?
答案 0 :(得分:1)
MySQL库使用%s
作为占位符。
mycursor.execute("SELECT name FROM workers WHERE symbol=%s", name)
尽管有相似之处,但这不是字符串替换。
答案 1 :(得分:1)
好的Spike7这正是理想的,
mycursor.execute("SELECT name FROM workers WHERE symbol=%s", (name,))
或
mycursor.execute("SELECT name FROM workers WHERE symbol=?", (name,))
the first link you given上接受的答案解释了evertything。
答案 2 :(得分:0)
您可以使用
mycursor.execute("SELECT name FROM workers WHERE symbol={}".format(name))
这仅在变量名不是字符串的情况下有效
答案 3 :(得分:-1)
mycursor.execute("SELECT name FROM workers WHERE symbol=%s"% name)
那是