Discord.py MySQL 连接器插入查询

Discord.py MySQL Connector INSERT into query

希望一些优秀的人可以帮助我解决这个问题,因为我超级卡住了,对我来说一切看起来都是正确的,但我的命令没有向数据库添加任何东西。所以我想要实现的是,当我键入 q!newuser "name" & "discord" 时,它会将值添加到数据库

这里是:

bot.py

from discord.ext import commands
import os

from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config


client = commands.Bot(command_prefix='q!')


@client.command()
async def load(ctx, extension):
    client.load_extension(f'cogs.{extension}')


@client.command()
async def unload(ctx, extension):
    client.unload_extension(f'cogs.{extension}')


for filename in os.listdir(f'./cogs'):
    if filename.endswith('.py'):
        client.load_extension(f'cogs.{filename[:-3]}')


def connect():
    """ Connect to MySQL database """

    db_config = read_db_config()
    conn = None
    try:
        print('Connecting to MySQL database...')
        conn = MySQLConnection(**db_config)

        if conn.is_connected():
            print('Connection established.')
        else:
            print('Connection failed.')

    except Error as error:
        print(error)

    finally:
        if conn is not None and conn.is_connected():
            conn.close()
            print('Connection closed.')


if __name__ == '__main__':
    connect()

client.remove_command('help')
client.run('mytoken')

python_mysql_dbconfig.py

from configparser import ConfigParser


def read_db_config(filename='config.ini', section='mysql'):
    """ Read database configuration file and return a dictionary object
    :param filename: name of the configuration file
    :param section: section of database configuration
    :return: a dictionary of database parameters
    """
    # create parser and read ini configuration file
    parser = ConfigParser()
    parser.read(filename)

    # get section, default to mysql
    db = {}
    if parser.has_section(section):
        items = parser.items(section)
        for item in items:
            db[item[0]] = item[1]
    else:
        raise Exception('{0} not found in the {1} file'.format(section, filename))

    return db

config.ini

[mysql]
host = localhost
database = bot_database
user = root
password = mypass
auth_plugin = mysql_native_password

现在执行我的命令:

newuser.py

import database
from discord.ext import commands


class Newuser(commands.Cog):

    def __init__(self, client):
        self.client = client

    @commands.command(name="newuser")
    @commands.has_permissions(administrator=True)
    async def insert_user(self, ctx, *args):
        try:
            name = ' '.join(args)
            discord = ' '.join(args)
        except IndexError:
            try:
                name = ' '.join(args)
                age = ' '.join(args)
            except ValueError:
                await ctx.send("Please enter a name")
                return
            except IndexError:
                await ctx.send("Please add users details")
                return
        add = database.insert_user(player_name=name, discord_tag=discord)
        if isinstance(add, Exception):
            await ctx.send(f"Database error when adding a new admin:\n```\n{add}\n```")
            return
        await ctx.send("Added the role to my admin list.")


def setup(client):
    client.add_cog(Newuser(client))

和我的插入查询

database.py

from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config

    ########################################################
    ################### MySQL Defines ######################
    ###################   Testing     ######################
    ########################################################
    
    def insert_user(player_name, discord_tag):
        try:
            db_config = read_db_config()
            conn = MySQLConnection(**db_config)
            c = conn.cursor()
            c.execute(
                "INSERT INTO 'user_management' ('player_name', 'discord_tag') values((%s, %s);",
                player_name, discord_tag)
            conn.commit()
            c.close()
        except Error as e:
            return e

抱歉,它有点冗长 post,但我对 python 还很陌生,想提供我拥有的所有文件。同样,一切似乎都有效,但我的“Mysql”数据库中没有任何内容,并且 pycharm 没有显示任何错误。

感谢您抽出时间帮我检查一下。

谢谢, 本

我认为您的查询有错字。虽然不知道为什么不报错
你有没有试过做更广泛的事情,比如

except Exception as e:
    return e

对于 insert_user?
似乎异常正在某处静默处理,但根据您提供的信息,我无法弄清楚原因。

附带说明一下,discord 提出了一种处理异常的特殊方法:discordpy error-handling.
乍一看似乎违反直觉,但它确实有助于确定问题和排除故障。