In this PyQt5 article we are going to talk about PyQt5 Inserting to Mysql Database with PyQt5, so first of all you can read PyQt5 Mysql Database Connection article . OK now we are going to start our topic and also remember that we are using Wamp server as our virtual server.
First we need some imports from PyQt5 also because of Database functionality we are using MYSQLdb, you can read my article about MYSQLdb in the PyQt5 Database Connection.
1 2 3 4 |
from PyQt5 import QtGui from PyQt5.QtWidgets import QApplication, QDialog, QLineEdit, QPushButton, QMessageBox, QVBoxLayout import sys import MySQLdb as mdb |
After that we are going to create our Window class that extends from QDialog and we add our Window requirements in the constructor of the class. we create two methods in the class, the first method is for setting our Window requirements in PyQt5, also we create a QVBoxLayout with two QLineEdit and one QPushButton. the second method is the method that we do our Database functionality i mean inserting data from the QLineEdit to Mysql database, first we do connection by using mdb.connect() and in the connect() we add our localhost, username, password and database name, remember that mdb is an alias to MYSQLdb, after that we execute our query and give a QMessageBox to the user for successfully inserting data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
class Window(QDialog): def __init__(self): super().__init__() self.title = "PyQt5 Insert Data" self.top = 100 self.left = 100 self.width = 300 self.height = 100 self.InitWindow() def InitWindow(self): self.setWindowIcon(QtGui.QIcon("codeloop.png")) self.setWindowTitle(self.title) self.setGeometry(self.top, self.left, self.width, self.height) vbox = QVBoxLayout() self.name = QLineEdit(self) self.name.setPlaceholderText('Please Enter Your Name') self.name.setStyleSheet('background:yellow') self.name.setFont(QtGui.QFont("Sanserif", 15)) vbox.addWidget(self.name) self.email = QLineEdit(self) self.email.setPlaceholderText('Please Enter Your Email') self.email.setFont(QtGui.QFont("Sanserif", 15)) self.email.setStyleSheet('background:yellow') vbox.addWidget(self.email) self.button = QPushButton("Insert Data", self) self.button.setStyleSheet('background:green') self.button.setFont(QtGui.QFont("Sanserif", 15)) vbox.addWidget(self.button) self.button.clicked.connect(self.InsertData) self.setLayout(vbox) self.show() def InsertData(self): con = mdb.connect('localhost', 'root', '', 'pyqt5') with con: cur = con.cursor() cur.execute("INSERT INTO data(name, email)" "VALUES('%s', '%s')" % (''.join(self.name.text()), ''.join(self.email.text()))) QMessageBox.about(self,'Connection', 'Data Inserted Successfully') self.close() |
Also every PyQt5 application must create an application object.
1 |
App = QApplication(sys.argv) |
This is the mainloop of the application. The event handling starts from this point.
1 2 |
window = Window() sys.exit(App.exec()) |
Complete source code for this example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
from PyQt5 import QtGui from PyQt5.QtWidgets import QApplication, QDialog, QLineEdit, QPushButton, QMessageBox, QVBoxLayout import sys import MySQLdb as mdb class Window(QDialog): def __init__(self): super().__init__() # Window properties self.title = "Codeloop.org - PyQt5 Insert Data" self.top = 100 self.left = 100 self.width = 300 self.height = 100 # Initialize window self.InitWindow() def InitWindow(self): # Set window properties self.setWindowIcon(QtGui.QIcon("codeloop.png")) self.setWindowTitle(self.title) self.setGeometry(self.top, self.left, self.width, self.height) # Create vertical layout for widgets vbox = QVBoxLayout() # Create QLineEdit for name input self.name = QLineEdit(self) self.name.setPlaceholderText('Please Enter Your Name') self.name.setStyleSheet('background:yellow') self.name.setFont(QtGui.QFont("Sanserif", 15)) vbox.addWidget(self.name) # Create QLineEdit for email input self.email = QLineEdit(self) self.email.setPlaceholderText('Please Enter Your Email') self.email.setFont(QtGui.QFont("Sanserif", 15)) self.email.setStyleSheet('background:yellow') vbox.addWidget(self.email) # Create QPushButton for inserting data self.button = QPushButton("Insert Data", self) self.button.setStyleSheet('background:green') self.button.setFont(QtGui.QFont("Sanserif", 15)) vbox.addWidget(self.button) # Connect button click event to InsertData method self.button.clicked.connect(self.InsertData) # Set layout for dialog window self.setLayout(vbox) # Show dialog window self.show() def InsertData(self): # Connect to MySQL database con = mdb.connect('localhost', 'root', '', 'pyqt5') with con: # Creat cursor object cur = con.cursor() # Execute SQL query to insert data into the database cur.execute("INSERT INTO data(name, email)" "VALUES('%s', '%s')" % (''.join(self.name.text()), ''.join(self.email.text()))) # Display success message using QMessageBox QMessageBox.about(self,'Connection', 'Data Inserted Successfully') # Close dialog window self.close() # Create the application instance App = QApplication(sys.argv) # Create main window instance window = Window() # Start application event loop sys.exit(App.exec()) |
Run the complete code and this will be the result
FAQs:
How to add data from Python to MySQL?
For adding data from Python to MySQL, you can follow these steps:
- Create a connection to the MySQL database using Python library such as MySQLdb, mysql-connector-python or PyMySQL.
- Create cursor object to execute SQL queries.
- Execute an SQL INSERT statement to add data to the database table, and specify the data values to be inserted.
- Commit the transaction to save the changes to the database.
- Close the cursor and database connection when done.
How to add dataset to MySQL?
For adding a dataset (multiple records) to MySQL database from Python, you can use a loop to iterate over the dataset and insert each record into the database table individually. Also you can use bulk insert methods provided by the database connector library, if available, for more efficient insertion of large datasets.
Subscribe and Get Free Video Courses & Articles in your Email
mugüeno
File “C:\Users\naomi\Desktop\Projet_Noe\inserttest.py”, line 65, in InsertData
with con:
AttributeError: __enter__
There is a problem, but why ?
check your database and fields
Traceback (most recent call last):
File “/data/user/0/ru.iiec.pydroid3/files/temp_iiec_codefile.py”, line 5, in
import MySQLdb as mdb
ModuleNotFoundError: No module named ‘MySQLdb’
You need to install mysqlclient pip install mysqlclient
TypeError: __init__() takes 1 positional argument but 5 were given
please helpp
data not insert