codeofandrin
codeofandrin

Reputation: 1557

discord.py: MySQL 'Cursor is not connected'

I'm trying to store data in my local database before kicking a member of a guild. I have the database setup in another file. I'm calling the kick function in another file. What I noticed is that sometimes it works and when I do it again it doesn't work anymore.

My code:

# Database.py

import os
import mysql.connector

from dotenv import load_dotenv

load_dotenv()


def modlog_db_connex():
    class ModLogDB:
        def __init__(self, connection, mycursor):
            self.connection = connection
            self.mycursor = mycursor

    modlog_db = mysql.connector.connect(
        host=os.getenv("DB_HOST"),
        user=os.getenv("DB_USERNAME"),
        password=os.getenv("DB_PASSWORD"),
        database=os.getenv("DB_NAME"),
        use_unicode=True
    )

    mycursor = modlog_db.cursor()
    return ModLogDB(modlog_db, mycursor)


# Kick.py

import discord

import GlobalSupport
import Database

moderator_above = GlobalSupport.moderator_above
modlog_db = Database.modlog_db_connex()


async def kick(client, ctx, member, reason):
  
      author_id = ctx.author.id
      log_channel = GlobalSupport.moderation_logs
      if any(role.id in moderator_above for role in ctx.author.roles) and author_id != int(member.id):

          if reason is None:
              reason = "None provided."

          sql = "INSERT INTO RLH_Cases_v2 (UserID, ModeratorID, CaseType, Reason) VALUES (%s, %s, %s, %s)"
          val = (str(member.id), str(ctx.author.id), "Kick", reason)
          modlog_db.mycursor.execute(sql, val)
          modlog_db.connection.commit()
          case_id = str(modlog_db.mycursor.lastrowid)
          modlog_db.connection.close()

          # ...

Error:

Traceback (most recent call last):
  File "C:\Users\user\Desktop\Team Stuff (TS, DC, MC)\RLH\Programming\OnMessage.py Rewrite\Commands\Kick.py", line 31, in kick
    modlog_db.mycursor.execute(sql, val)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\mysql\connector\cursor_cext.py", line 242, in execute
    raise errors.ProgrammingError("Cursor is not connected", 2055)
mysql.connector.errors.ProgrammingError: 2055: Cursor is not connected

Upvotes: 0

Views: 1590

Answers (1)

Stoobish
Stoobish

Reputation: 1382

You're closing the connection to your MySQL database after each kick and don't reconnect prior to calling kick again.

Upvotes: 1

Related Questions