How to use databases for data storage and retrieval in PyQt5?

In PyQt5, the QtSql module can be used to connect to a database and perform data storage and retrieval operations. Below is a simple example demonstrating how to use SQLite database for data storage and retrieval:

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QLabel, QLineEdit, QMessageBox
from PyQt5.QtSql import QSqlDatabase, QSqlQuery

class DatabaseExample(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Database Example')
        
        layout = QVBoxLayout()
        
        self.name_label = QLabel('Name:')
        self.name_edit = QLineEdit()
        
        self.save_button = QPushButton('Save')
        self.save_button.clicked.connect(self.save_data)
        
        self.retrieve_button = QPushButton('Retrieve')
        self.retrieve_button.clicked.connect(self.retrieve_data)
        
        layout.addWidget(self.name_label)
        layout.addWidget(self.name_edit)
        layout.addWidget(self.save_button)
        layout.addWidget(self.retrieve_button)
        
        self.setLayout(layout)
        
        self.db = QSqlDatabase.addDatabase('QSQLITE')
        self.db.setDatabaseName('data.db')
        
        if not self.db.open():
            QMessageBox.critical(None, 'Error', 'Could not open database')
        
    def save_data(self):
        name = self.name_edit.text()
        
        query = QSqlQuery()
        query.prepare('INSERT INTO users (name) VALUES (?)')
        query.bindValue(0, name)
        
        if not query.exec():
            QMessageBox.critical(None, 'Error', 'Could not save data')
        else:
            QMessageBox.information(None, 'Success', 'Data saved successfully')
            
    def retrieve_data(self):
        query = QSqlQuery()
        query.prepare('SELECT name FROM users')
        
        if query.exec():
            while query.next():
                name = query.value(0)
                print(name)
        else:
            QMessageBox.critical(None, 'Error', 'Could not retrieve data')
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = DatabaseExample()
    window.show()
    sys.exit(app.exec_())

In the example above, we have created a simple GUI application that includes a text box and two buttons. Users can input their name and click the “Save” button to save the data to an SQLite database. Users can also click the “Retrieve” button to retrieve all data from the database.

Before running this example, it is necessary to install the PyQt5 and sqlite3 modules. You can use the following commands to install these modules:

pip install PyQt5
pip install pysqlite3

In practical applications, database connection information and SQL query statements can be modified as needed to suit different scenarios.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds