I am on a hobby project, working on a python mysql database, where I simple make the connection and perform some basic action, but when I run it give me reference error. My whole code looks like;
# My Mysql Library
import mysql.connector
#My Database class
class Database(object):
# Class Attributes
connection = None
cursor = None
TABLE_NAME = "customer"
# My constructor
def __init__(self):
""" This constructor is used to connect the database with my python application
and make the connection object and then create the cursor object with help
of it we create the table if not exists """
connection = mysql.connector.connect(
host="localhost",
user="root",
password="mypassword",
database="mydb"
)
# Initialize the cursor
self.cursor = connection.cursor()
# Create Individual Table
self.cursor.execute(f"""
CREATE TABLE IF NOT EXISTS {self.TABLE_NAME}(
cust_id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
cust_name VARCHAR(35),
cust_f_name VARCHAR(35),
cust_cno INTEGER(20) UNIQUE,
cust_address VARCHAR(50)
);
""")
def insert_data(self, name, f_name, cno, address):
""" This method is used to insert the value which is provided by user
With the help of GUI """
# self.cursor.execute(f"""
# INSERT INTO {Database.TABLE_NAME}(cust_name, cust_f_name, cust_cno, cust_address)
# VALUES (%, %, %, %, %)
# """, (name, f_name, cno, address))
# Insert Query
insert_query = f"""
INSERT INTO {Database.TABLE_NAME}(
cust_name, cust_f_name, cust_cno, cust_address
) VALUES (%, %, %, %);
"""
# Tuple of values which is to me inserted into the database
values = (name, f_name, cno, address)
# Execute the query and commit the data
self.cursor.execute(insert_query, values)
self.commit_data()
def commit_data(self):
""" This method is used to save all the data inside the db after data insertion"""
self.connection.commit()
def close_db(self):
""" This will close the database connection and cursor after performing everything"""
self.cursor.close()
self.connection.close()
# Main Body
db = Database()
db.insert_data("feezan", "noor", 552, "shaidu")
**But When I run it give the following error**
Traceback (most recent call last): File "C:/Users/Feezan Khattak/OneDrive/Documents/My programming/Python Programming/PyQt5 Disgner/7- Data Entry With Images/Database/MyDatabase.py", line 72, in db.insert_data("feezan", "noor", 552, "shaidu") File "C:/Users/Feezan Khattak/OneDrive/Documents/My programming/Python Programming/PyQt5 Disgner/7- Data Entry With Images/Database/MyDatabase.py", line 58, in insert_data self.cursor.execute(insert_query, values) File "C:\Users\Feezan Khattak\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\cursor_cext.py", line 232, in execute if not self._cnx: ReferenceError: weakly-referenced object no longer exists
I will be highly appreciated your answers.