在 python 中使用 IN 子句插入一个值时出错

Error while inserting one value with IN clause in python

mycursor.execute("update member set group_id = %s where member_id IN {}".format(tuple(event["body-json"]["member_ids"])),group_id)

它对列表中超过 1 个值的工作正常 - event["body-json"]["member_ids"] 但在对列表中的单个值执行相同操作时失败并生成异常

适用于

{
    "group_id":"1",
    "member_ids": [1,2,3]
}

错误 - 尝试

{
    "group_id":"1",
    "member_ids": [1]
}

{
    "errorMessage": "(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 ')' at line 1\")",
    "errorType": "ProgrammingError",
    "stackTrace": [
        "  File \"/var/task/lambda_function.py\", line 72, in lambda_handler\n    mycursor.execute(\"update member set group_id = %s where member_id IN {}\".format(tuple(event[\"body-json\"][\"member_ids\"])),group_id)\n",
        "  File \"/var/task/pymysql/cursors.py\", line 170, in execute\n    result = self._query(query)\n",
        "  File \"/var/task/pymysql/cursors.py\", line 328, in _query\n    conn.query(q)\n",
        "  File \"/var/task/pymysql/connections.py\", line 517, in query\n    self._affected_rows = self._read_query_result(unbuffered=unbuffered)\n",
        "  File \"/var/task/pymysql/connections.py\", line 732, in _read_query_result\n    result.read()\n",
        "  File \"/var/task/pymysql/connections.py\", line 1075, in read\n    first_packet = self.connection._read_packet()\n",
        "  File \"/var/task/pymysql/connections.py\", line 684, in _read_packet\n    packet.check_error()\n",
        "  File \"/var/task/pymysql/protocol.py\", line 220, in check_error\n    err.raise_mysql_exception(self._data)\n",
        "  File \"/var/task/pymysql/err.py\", line 109, in raise_mysql_exception\n    raise errorclass(errno, errval)\n"
    ]

PyMySQL 支持传递元组和列表作为参数,其中需要括号中的逗号分隔列表:

mycursor.execute("UPDATE member SET group_id = %s WHERE member_id IN %s",
                 (group_id, event["body-json"]["member_ids"]))

错误源于 Python 表示单项元组的方式:

In [8]: tuple([1])
Out[8]: (1,)

在 SQL 中,尾随逗号是一个语法错误。