i'm having some trouble in order to make a cog with the discordpy rewrite branch in python.
I'm trying to make a command to start a connection to a database using mysql connector and to create a simple table. The problem is that when i define a cursor variable like stated in the official mysql docs i get an error: "local variable 'cnx' referenced before assignment"
Now this is the code:
import discord
from discord.ext import commands
import json
import asyncio
import mysql.connector
from mysql.connector import errorcode
with open("config.json") as configfile:
config = json.load(configfile)
class testcog:
def __init__(self, client):
self.client = client
@commands.command()
async def dbconnect(self, ctx):
await ctx.message.author.send('I\'m connecting to the database, please be patient.')
try:
cnx = mysql.connector.connect(user=config['sqlconfig']['user'], password=config['sqlconfig']['password'],
host=config['sqlconfig']['host'],
database=config['sqlconfig']['database'])
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
cnx.close()
cursor = cnx.cursor()
TABLES = {}
TABLES['employee'] = (
"CREATE TABLE `employee` ("
" `emp_no` int(11) NOT NULL AUTO_INCREMENT,"
" `birth_date` date NOT NULL,"
" `first_name` varchar(14) NOT NULL,"
" `last_name` varchar(16) NOT NULL,"
" `gender` enum('M','F') NOT NULL,"
" `hire_date` date NOT NULL,"
" PRIMARY KEY (`emp_no`)"
") ENGINE=InnoDB")
for table_name in TABLES:
table_description = TABLES[table_name]
try:
print("Creating table {}: ".format(table_name), end='')
cursor.execute(table_description)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
print("already exists.")
else:
print(err.msg)
else:
print("OK")
cursor.close()
cnx.close()
def setup(client):
client.add_cog(testcog(client))
The table and the code to create it was copied directly from the official docs.
The piece of code that gives me the error is : cursor = cnx.cursor()
just before the TABLES
dictionary is created.
I don't understand what i'm doing wrong, help is much appreciated.
cnx.cursor()
even thoughcnx
in undefined. You should add areturn
in theexcept
block. Also, thatelse
block doesn't look right, i'm not sure what that's supposed to do, but it looks like it closes the connection as soon as it opens. - Patrick Haughelse
statement of the try block it gives me that error of thecursor = cnx.cursor()
. I use the cnx in the try block so how's possible that the error says that i'm using cnx before defining it? - Emmanuele D'Ettorre