python - 为什么我的 python 代码没有写入 MYSQL 数据库,使用实用程序代码文件
问题描述
我正在寻求帮助,我的目标是为我的不和谐机器人的数据库更新循环。但是,它只是拒绝写入数据库,但循环将运行。我究竟做错了什么?
我知道它以前工作过,但到目前为止,它还没有写入数据库。
import mysql.connector
from util.db_tools import connect, execute, execute_data_input, close
from mysql.connector import errorcode
class tasks(commands.Cog):
def __init__(self, client):
self.client = client
self.index = 0
self.update.start()
@tasks.loop(minutes=1)
async def update(self):
print("Updating...")
async for guild in self.client.fetch_guilds():
channels = await guild.fetch_channels()
members = await guild.fetch_members().flatten()
channel_count = len(channels)
members_count = len(members)
update_date = datetime.now()
# add data to stats table
bans = await guild.bans()
ban_count = len(bans)
# To add new row each day
add_bans = ("INSERT INTO stats"
"(member_count, bans)"
"VALUES (%s, %s)"
)
data_bans = (members_count, ban_count)
connect(guild.id)
logging = (
'''
INSERT INTO logging (server, message_edit, message_deletion=, role_changes, name_update, member_movement, avatar_changes, bans, ignored_channels) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
'''
)
data = (str(guild.id), 0, 0, 0, 0, 0, 0, 0, None)
execute_data_input(logging, data)
execute_data_input(add_bans, data_bans)
close()
async for member in guild.fetch_members():
member_id = member.id
displayName = member.display_name
discriminator = member.discriminator
mention = member.mention
# update existing
User = discord.Member
dm = User.dm_channel
# Updates the following info daily
update_user = (
"UPDATE users SET display_name='{}', discriminator='{}', mention='{}', dm_channel='{}', server='{}', id='{}', names='{}' WHERE user_id='{}'".format(
displayName, discriminator, mention, dm, guild.name, member.id, str(displayName), member_id))
update_Guild = (
"UPDATE servers SET prefix='{}', id='{}', Member_Count='{}', Channels='{}', Last_Update='{}' WHERE Server_ID='{}'".format(
PREFIX, guild.id, members_count, channel_count, update_date, guild.id))
connect(guild.id)
execute(update_user)
close()
connect("discord")
execute(update_Guild)
close()
def setup(client):
client.add_cog(tasks(client))
我需要帮助的部分是@tasks 循环。
我知道与 MySQL 服务器的连接在那里,因为我的实用程序代码返回
Connected to MySQL Server version 5.7.35-0ubuntu0.18.04.1
You're connected to database: ('793077301935865876',)
Connection Closed.
在控制台中。如果我错了,请纠正我,但这意味着 MySQL 脚本在某种程度上是错误的。虽然我不确定如何解决正在发生的事情。
util.db_tools
import mysql.connector
from mysql.connector import errorcode
import sys
def exists():
File = open("data_bool.txt", "r")
return File.read()
def write(ctx):
File = open("data_bool.txt", "w")
File.write(ctx)
def connect(self):
global cnx
global cursor
try:
database_name = self
cnx = mysql.connector.connect(
host='192.168.86.41',
user='admin',
password='Shellshocker93!',
database=f"{database_name}"
)
# exception occurred
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print(f'\033[1;31m Something is wrong with your user name or password')
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print(f'\033[1;31m Database does not exist')
else:
print(f'\033[1;31m {err}')
if cnx.is_connected():
db_Info = cnx.get_server_info()
print(f'\033[1;32m Connected to MySQL Server version\033[0;33m ', db_Info)
cursor = cnx.cursor()
cursor.execute("select database();")
record1 = cursor.fetchone()
record =record1[0]
print(f'\033[1;32m You\'re connected to database: \033[3;34m', record)
def fetchall():
cursor.fetchall()
def execute(ctx):
try:
write('False')
cursor.execute(ctx, multi=True)
cnx.commit()
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print(f'\033[1;31m Something is wrong with your user name or password')
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print(f'\033[1;31m Database does not exist')
elif err.errno == errorcode.ER_DUP_ENTRY:
print(f'\033[1;32m Entry already exists.')
write('True ')
return
else:
print(f'{err}\n' + f"{ctx}")
def execute_data_input(ctx, ctx1):
try:
write('False')
cursor.execute(ctx, ctx1, multi=True)
cnx.commit()
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print(f'\033[1;31m Something is wrong with your user name or password')
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print(f'\033[1;31m Database does not exist')
elif err.errno == errorcode.ER_DUP_ENTRY:
print(f'\033[1;32m entry already exists.')
write('True ')
return
else:
print(f'{err}\n' + f"{ctx} \n {ctx1}")
def close():
cursor.close()
cnx.close()
print(f"\033[0;32m Connection Closed. \n")
def commit():
cnx.commit()
解决方案
推荐阅读
- eclipse - Maven 和 EJB (JEE)
- html - 主体上带有 Webpack 和 Symfony 的背景颜色
- ffmpeg - 使用 ss 后输出流中的非单调 DTS
- docker - docker私有注册表作为本地机器和服务器机器中的默认注册表
- elasticsearch - Elaticsearch 对单词少的文档有好处吗
- javascript - 在 lit-element 中重用 firebase 常量
- android - 为什么只获取用户名?
- phpmyadmin - PhpMyAdmin 无法加密到 MD5
- r - 加载Javascript后反应输入不起作用
- ruby - 将优雅的方式添加到已包含的模块中?