Python代码:
query是一个UPDATE查询,错误仅说明元组存在问题,该元组作为参数传递给IN子句
pyList是Python列表,DBOBJ是连接对象
pyTuple = tuple(pyList)
print(pyTuple)
pyTupleSQLFormat = DBOBJ.string_literal(pyTuple)
print(pyTupleSQLFormat)
query = "UPDATE seats SET isReserved = 1 WHERE screen_name='{}' AND seat_number IN %s".format(screenname)
args = (pyTupleSQLFormat,)
CurOBJ.execute(query,args)
控制台输出:Python
('B1', 'B2', 'A6', 'A7')
b"'(\\'B1\\', \\'B2\\', \\'A6\\', \\'A7\\')'"
(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 ''\\'(\\\\\\'B1\\\\\\', \\\\\\'B2\\\\\\', \\\\\\'A6\\\\\\', \\\\\\'A7\\\\\\')\\''' at line 1")
答案 0 :(得分:0)
string_literal(...)
似乎正在准备将对象插入到char / text字段中,而不是以可以附加到查询的方式对其进行字符串化。
您可以通过dynamically building parameter placeholders将元组内容作为附加参数传递给查询。这还有使用参数化来避免SQL注入和相关问题的另一个优点。
screen_name = "example"
seat_numbers = [1, 2, 3, 4]
args = tuple([screen_name] + seat_numbers)
query = """
UPDATE
seats
SET
isReserved = 1
WHERE
screen_name=%s AND
seat_number IN ({placeholders})
""".format(
placeholders=",".join(["%s"] * len(seat_numbers)),
)
print(query)
print(args)
cursor.execute(query, args)