Discord.py MySQL连接器插入查询
希望一些优秀的人能帮我解决这个问题,因为我被卡住了,对我来说一切看起来都是正确的,但我的命令并没有向数据库添加任何内容。所以我想要实现的是当我输入q!newuser“name”和“discord”它将值添加到数据库中 下面是: 机器人 python\u mysql\u dbconfig.py config.ini 现在听我的命令: newuser.py 和我的插入查询 database.py 抱歉,这是一篇冗长的文章,但我对python相当陌生,希望提供我拥有的所有文件。同样,所有这些看起来都正常,但在我的“Mysql”数据库中什么也没有出现,pycharm也没有显示任何错误 谢谢你花时间帮我看一下 谢谢,,Discord.py MySQL连接器插入查询,mysql,discord.py,mysql-connector,Mysql,Discord.py,Mysql Connector,希望一些优秀的人能帮我解决这个问题,因为我被卡住了,对我来说一切看起来都是正确的,但我的命令并没有向数据库添加任何内容。所以我想要实现的是当我输入q!newuser“name”和“discord”它将值添加到数据库中 下面是: 机器人 python\u mysql\u dbconfig.py config.ini 现在听我的命令: newuser.py 和我的插入查询 database.py 抱歉,这是一篇冗长的文章,但我对python相当陌生,希望提供我拥有的所有文件。同样,所有这些看起来都正
本我想你的查询有错。虽然我不知道为什么不会出现错误。
你试过做更广泛的事情吗,比如
例外情况除外,如e:
返回e
对于插入用户?
似乎异常正在某个地方悄无声息地处理,但从您提供的信息来看,我不明白为什么
另一方面,discord提出了一种处理异常的特殊方法:。
乍一看,这似乎有悖常理,但它确实有助于确定问题并排除故障。感谢您指出,我现在修复了一个拼写错误,并且工作正常
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')
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
[mysql]
host = localhost
database = bot_database
user = root
password = mypass
auth_plugin = mysql_native_password
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))
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