python 我希望变量从数据库中以整数格式获取值并存储

7hiiyaii  于 2023-01-16  发布在  Python
关注(0)|答案(1)|浏览(108)

bounty将在6天后过期。回答此问题可获得+50的声望奖励。Mudit Dagar正在寻找规范答案:请帮我解决这个问题,并采取50信誉

import discord
import mysql.connector
client = discord.Client(intents=discord.Intents.all())
mylb = mysql.connector.connect(
    host='localhost',[![enter image description here][1]][1]
    user='root',
    password="",
    database="worst")
cursor = mylb.cursor()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    
    if message.author == client.user:
        return

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')
    if message.content.startswith('$howareyou'):
        await message.channel.send('fine')
    a = 0
    if message.content.startswith('$cash'):
        cursor.execute("select cash from mudit")
        
        b = cursor.fetchone()
        await message.channel.send(b[0])
        c = int(b[0])
    if message.content.startswith('$daily'):
        a = a+10
        await message.channel.send(a)
        sql = ("""UPDATE mudit SET cash = (%s) WHERE id = (1)"""%(c+10))
        # sql = "insert into mudit (id,cash) values (%s,%s)"
      
        cursor.execute(sql)
        mylb.commit()
  
client.run('my token')
UnboundLocalError: cannot access local variable 'c' where it is not associated with a 
value

在这段代码中,我希望变量c以整数格式获取值,并将其存储在数据库的cash列中,我解压缩了列表,并将解压缩后的值转换为整数,但变量c仍然没有将值存储为文字。

i7uaboj4

i7uaboj41#

以下是具体操作方法(注:像这样使用全局变量并不理想,但这至少可以让你开始):

import discord
import mysql.connector
...
client = 
mylb = 
cursor = 
c = None    # Declare a global "c".

@client.event
async def on_ready():
...

@client.event
async def on_message(message):
    ...
    if message.content.startswith('$cash'):
        ...
        #
        # Write to the global c.
        #
        global c
        c = int(b[0])
    if message.content.startswith('$daily'):
        a = a+10
        await message.channel.send(a)
        #
        # Check that c has previously been set.
        #
        assert c is not None
        sql = ("""UPDATE mudit SET cash = (%s) WHERE id = (1)"""%(c+10))
        # sql = "insert into mudit (id,cash) values (%s,%s)"
      
        cursor.execute(sql)
        mylb.commit()

这是因为c的全局声明是在$cash事件发生时编写的,而全局c是在$daily事件发生时使用的。当然,如果你的事件以意外的顺序到达,或者你得到了重复,或者你有多个线程,等等,所有类型的问题都可能发生。

相关问题