Python类型元组无法转换为MySQL
我真的不明白元组是怎么工作的。但我知道的是它们看起来像这样Python类型元组无法转换为MySQL,python,mysql,sql,discord.py,discord.py-rewrite,Python,Mysql,Sql,Discord.py,Discord.py Rewrite,我真的不明白元组是怎么工作的。但我知道的是它们看起来像这样 (1,变量) 但我一直在犯错误: 无法转换Python类型元组 有人能帮忙吗这是我的代码: @client.command() async def buy(ctx, item: str): USER_ID = ctx.message.author.id write_log("Buy command requested") #write_log("Sending GET re
(1,变量)
但我一直在犯错误:
无法转换Python类型元组
有人能帮忙吗这是我的代码:
@client.command()
async def buy(ctx, item: str):
USER_ID = ctx.message.author.id
write_log("Buy command requested")
#write_log("Sending GET request to Cosmos API...")
try:
SQL.execute("SELECT price FROM shop WHERE itemname = %s", (item,))
price = SQL.fetchone()
SQL.execute("SELECT balance FROM Accounts WHERE user_id = %s", (USER_ID,))
SQL.execute("UPDATE Accounts SET balance = balance - %s WHERE user_id = %s", (price, USER_ID))
db.commit()
await ctx.send(f"Successfully bought **{item}** for **{price} Rollars**.")
except Exception as ex:
write_log('ERROR')
full_traceback = traceback.format_exc()
write_log(f'Errored whilst sending ctx(embed), (about): {ex} {full_traceback}')
完整回溯:
Traceback (most recent call last):
File "Bot.py", line 316, in buy
SQL.execute("UPDATE Accounts SET balance = balance - %s WHERE user_id = %s", (price, USER_ID))
File "/home/vihanga/lib/python3.8/site-packages/mysql/connector/cursor_cext.py", line 248, in execute
prepared = self._cnx.prepare_for_mysql(params)
File "/home/vihanga/lib/python3.8/site-packages/mysql/connector/connection_cext.py", line 626, in prepare_for_mysql
result = self._cmysql.convert_to_mysql(*params)
_mysql_connector.MySQLInterfaceError: Python type tuple cannot be converted
非常感谢您能向我解释它是如何工作的,并可能帮助我解决错误。fetchone()函数将结果作为元组返回给您。因此,当您使用fetchone时,price变量中存储的值是如下所示的元组:(100,)
。
然后,当您执行更新查询时,您正在传递另一个元组中接收到的整个元组。例如,如果price值返回为100
,则下面是传递给execute函数的内容。
SQL.execute(“更新…”,((100),用户ID))
因此,参数的第一个元素是一个元组,而不是一个值,您会得到这个错误,因为数据库认为其中有一些值可以使用,但是因为它找到了一个元组,而不是第一个元素,所以您会得到这个错误。
您应该做的只是传递一个整数值作为price参数,这样它看起来像:SQL.execute(“UPDATE…..”,(100,USER_ID))
要做到这一点,您可以在元组前面放一个*来解压元组,或者像price[0]
那样从元组中获取第一个值