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.