1

I am attempting to create a function that initializes the MySQL + Python connection. Here is what I have so far:

import mysql.connector

MySQLConfig = {
  'user': 'user',
  'password': 'password',
  'host': 'localhost',
  'database': 'DB',
  'raise_on_warnings': True,
}

# Initialize MySQL Connection + Cursor
def createCursor():
    cnx = mysql.connector.connect(**MySQLConfig)
    cursor = cnx.cursor()
    return cursor

cursor = createCursor()

query = 'SHOW tables'
cursor.execute(query)

for row in cursor:
    print(row)

The code will run fine when not enclosed in the createCursor() function. Once I put it in one I receive the following error:

Traceback (most recent call last):
  File "./config.py", line 24, in <module>
    cursor.execute(query)
  File "/Library/Python/2.7/site-packages/mysql/connector/cursor.py", line 473, in execute
    if not self._connection:
ReferenceError: weakly-referenced object no longer exists

Any ideas on what I may need to do? I've tried returning the connection only and working with the cursor outside the function, that also results in the same error too.

1 Answer 1

3

As you have made cnx a local variable it is garbage collected at the end of function..
Do it something like this

cnx = mysql.connector.connect(**MySQLConfig)
# Initialize  Cursor
def createCursor():
    return cnx.cursor()

But that is a bad idea.My Approach would be something like this

import mysql.connector
class MysqlHelper:

    def __init__(self):
        MySQLConfig = {'user': 'user','password': 'password','host': 'localhost','database': 'DB','raise_on_warnings': True}
        self.cnx = mysql.connector.connect(**MySQLConfig) 
        self.cursor = self.cnx.cursor()

    def execute_query(self,query):
        self.cursor.execute(query)      
        for row in self.cursor:
            print(row)

mysql_helper = MysqlHelper()
mysql_helper.execute_query("SHOW tables")
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome thanks, exactly what I needed! Why exactly is it a bad idea though?
It is not good to create mysql cursor every time insted you create it as a global variable...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.