0

that is my code :

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import mysql.connector
import mysql.connector.cursor
from mysql.connector import errorcode
import sys
import os
from os import path
from PyQt5.uic import loadUiType
FORM_CLASS,_ = loadUiType(path.join(path.dirname(__file__),"mainwindow.ui"))
class Main(QMainWindow,FORM_CLASS):
 def __init__(self,parent=None):
 super(Main,self).__init__(parent)
 QMainWindow.__init__(self)
 self.setupUi(self)
 self.InitUI()
 self.Handel_buttons()
 self.Handel_db_connections()
 def InitUI(self):
 ## changes in the run time
 pass
 def Handel_buttons(self):
 ## all buttons in the app
 self.pushButton.clicked.connect(self.add_mahmoud_friends)
 self.pushButton_3.clicked.connect(self.update_mahmoud_friends)
 self.pushButton_2.clicked.connect(self.delete_mahmoud_friends)
 def Handel_db_connections(self):
 try:
 conn = mysql.connector.connect(host='localhost',
 database='mydb',
 user='root',
 password='*******',
 use_pure=True) # use_pure is set to true
 if conn.is_connected():
 db_Info = conn.get_server_info()
 print("Connected to MySQL database using C extension... MySQL Server version on ", db_Info)
 self.c = conn.cursor()
 except errorcode as e:
 print("Error while connecting to MySQL using C extension", e)
 finally:
 # closing database connection.
 if (conn.is_connected()):
 print("connection is closed")
 ####################################################
 ## mahmoud info
 def add_mahmoud_friends(self):
 mth_friends = self.lineEdit.text()
 self.c.execute('''INSERT INTO mtth (mth_friends) values (%s)''', (mth_friends))
 print("done")
 def update_mahmoud_friends(self):
 pass
 def delete_mahmoud_friends(self):
 pass
def main():
 app= QApplication(sys.argv)
 window =Main()
 window.show()
 app.exec_()
if __name__ == '__main__':
 main()

when I used that code connection is established but it causes that error on inserting information into SQL Database made by mysql workbench the error is:

Connected to MySQL database using C extension... MySQL Server version on 8.0.12
connection is closed
Traceback (most recent call last):
 File "/Users/mahmoudtarek/Desktop/mth1/index.py", line 60, in add_mahmoud_friends
 self.c.execute('''INSERT INTO mtth (mth_friends) values (%s)''', (mth_friends))
 File "/Users/mahmoudtarek/PycharmProjects/untitled/venv/lib/python3.7/site-packages/mysql/connector/cursor.py", line 533, in execute
 if not self._connection:
ReferenceError: weakly-referenced object no longer exists
Process finished with exit code 134 (interrupted by signal 6: SIGABRT)
eyllanesc
246k19 gold badges205 silver badges282 bronze badges
asked Sep 14, 2018 at 19:57

1 Answer 1

1

What you have to save is the connector, on the other hand the interaction with the database can bring problems so you must use try-except, you must also call commit() to execute the commands.

import sys
import os
from PyQt5 import QtCore, QtGui, QtWidgets, uic
import mysql.connector
from mysql.connector import errorcode
FORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__),"mainwindow.ui"))
class Main(QtWidgets.QMainWindow, FORM_CLASS):
 def __init__(self,parent=None):
 super(Main,self).__init__(parent)
 self.setupUi(self)
 self.InitUI()
 self.conn = None
 self.handle_buttons()
 self.handle_db_connections()
 def InitUI(self):
 ## changes in the run time
 pass
 def handle_buttons(self):
 ## all buttons in the app
 self.pushButton.clicked.connect(self.add_mahmoud_friends)
 self.pushButton_3.clicked.connect(self.update_mahmoud_friends)
 self.pushButton_2.clicked.connect(self.delete_mahmoud_friends)
 def handle_db_connections(self):
 try:
 self.conn = mysql.connector.connect(
 host='localhost',
 database='mydb',
 user='root',
 password='*******',
 use_pure=True) # use_pure is set to true
 if self.conn.is_connected():
 db_Info = self.conn.get_server_info()
 print("Connected to MySQL database using C extension... MySQL Server version on ", db_Info)
 except mysql.connector.Error as err:
 print("Error while connecting to MySQL using C extension", err)
 def add_mahmoud_friends(self):
 mth_friends = self.lineEdit.text()
 if self.conn:
 c = self.conn.cursor()
 try:
 c.execute('''INSERT INTO mtth (mth_friends) values (%s)''', (mth_friends,))
 self.conn.commit()
 except mysql.connector.Error as err:
 print("Error: ", err)
 def update_mahmoud_friends(self):
 pass
 def delete_mahmoud_friends(self):
 pass
 def closeEvent(self, event):
 if self.conn:
 self.conn.close()
 super(Main, self).closeEvent(event)
def main():
 app= QtWidgets.QApplication(sys.argv)
 window =Main()
 window.show()
 app.exec_()
if __name__ == '__main__':
 main()
answered Sep 14, 2018 at 20:59
Sign up to request clarification or add additional context in comments.

1 Comment

@mthafize19 If my answer helps you, do not forget to mark it as correct, if you do not know how to do it, review the tour, that is the best way to thank.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.