【问题标题】:Discord.py MySQL Connector INSERT into queryDiscord.py MySQL 连接器插入查询
【发布时间】:2021-06-07 06:12:10
【问题描述】:

希望一些很棒的人可以帮助我解决这个问题,因为我超级卡住了,对我来说一切似乎都是正确的,但我的命令没有向数据库添加任何内容。所以我想要实现的是,当我输入 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))

和我的插入查询

数据库.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

抱歉,这是一篇冗长的帖子,但我对 python 还很陌生,想提供我拥有的所有文件。同样,一切似乎都正常,但我的“Mysql”数据库中没有出现任何内容,并且 pycharm 没有显示错误。

感谢您花时间帮我检查这个。

谢谢, 本

【问题讨论】:

    标签: mysql discord.py mysql-connector


    【解决方案1】:

    我认为您的查询中有错字。虽然我不知道为什么不会出现错误。
    你有没有尝试过做一些更广泛的事情,比如

    except Exception as e:
        return e
    

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

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

    【讨论】:

    • 感谢您指出我有一个错字,我现在已修复此问题并且运行良好
    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 2011-03-29
    • 2020-07-22
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多