Python PyMySQL错误地将变量标识为元组

Python PyMySQL错误地将变量标识为元组,python,pymysql,Python,Pymysql,我试图在Python3中插入PyMySQL,但我一直得到以下结果: TypeError: unsupported operand type(s) for %: 'tuple' and 'tuple' 我的代码如下: query = ("INSERT INTO table_name ", "(type,sub) ", "VALUES ", "(%s,%s)") #Execute the quer

我试图在Python3中插入PyMySQL,但我一直得到以下结果:

TypeError: unsupported operand type(s) for %: 'tuple' and 'tuple'
我的代码如下:

query = ("INSERT INTO table_name ",
                 "(type,sub) ",
                 "VALUES ",
                 "(%s,%s)")
#Execute the query
print("Category: %s" % category)
print("Category is string:",isinstance(category,str))
print("Category_group: %s" % category_group)
print("Category_group is string:",isinstance(category,str))
self.DB['master']['cursor'].execute(query,(category,category_group,))
self.DB['master']['con'].commit()
当运行输出时:

Category: Amusement Park
Category is string: True
Category_group: Parks
Category_group is string: True
Traceback (most recent call last):
  File "main.py", line 87, in <module>
    m()
  File "main.py", line 82, in __call__
    self.deal.processdeal(deal=item,store=store)
  File "file.py", line 85, in processdeal
    btype = self.obtainBusinessType(deal['category'],deal['categoryGroup'])
  File "file.py", line 59, in obtainBusinessType
    self.DB['master']['cursor'].execute(query,(category,category_group,))
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pymysql/cursors.py", line 130, in execute
    query = query % self._escape_args(args, conn)
TypeError: unsupported operand type(s) for %: 'tuple' and 'tuple'
类别:游乐园
类别为字符串:True
组别:公园
类别组为字符串:True
回溯(最近一次呼叫最后一次):
文件“main.py”,第87行,在
m()
调用中第82行的文件“main.py”__
self.deal.processdeal(交易=物品,商店=商店)
processdeal中第85行的文件“File.py”
btype=self.obtainBusinessType(交易['category'],交易['categoryGroup'])
文件“File.py”,第59行,在获取业务类型中
self.DB['master']['cursor'].execute(查询,(类别,类别组,)
文件“/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site packages/pymysql/cursors.py”,第130行,在execute中
查询=查询%self.\u转义\u参数(参数,conn)
TypeError:不支持%的操作数类型:'tuple'和'tuple'

输出语句表明我正在将字符串作为参数输入,那么为什么它会抱怨元组呢?

您的问题是如何构建
查询
变量

query = ("INSERT INTO table_name ",
             "(type,sub) ",
             "VALUES ",
             "(%s,%s)")
print query 
>>>('INSERT INTO table_name ', '(type,sub) ', 'VALUES ', '(%s,%s)')

query = query % ('hello', 'world')
TypeError:不支持%的操作数类型:'tuple'和'tuple'

请注意,您的
查询如何作为
元组输出,这会导致错误

您可以使用
str

query = "INSERT INTO table_name (type,sub) VALUES (%s,%s)"
或者从查询中删除

query = ("INSERT INTO table_name "
              "(type,sub) "
              "VALUES "
              "(%s,%s)")
或者,正如Kindall所述,您也可以对多行字符串使用三重引号

"""INSERT INTO table_name 
           (type,sub) 
           VALUES
           (%s,%s)"""

您甚至不需要“\”。实际上,考虑一下,三重引号可能是一种解决方案。这是一种解决方案,但三重引号不是通常用于注释块吗?不,三重引号用于多行字符串文字。docstring(不是注释)通常是多行字符串文本,因此在那里使用它们,但是还有很多其他情况需要多行字符串文本。