Search code examples
pythonpyqt5qtablewidget

In Python: Insert all Entries in a QtableWidget into Database Table at once


wonder if someone knows how to insert with python all entries of a qtablewidget into a database. So far i found this coding:

# Creating a query for later execution using .prepare()
insertDataQuery = QSqlQuery()
insertDataQuery.prepare(
    """
    INSERT INTO contacts (
        name,
        job,
        email
    )
    VALUES (?, ?, ?)
    """
)

# Sample data
data = [
    ("Joe", "Senior Web Developer", "[email protected]"),
    ("Lara", "Project Manager", "[email protected]"),
    ("David", "Data Analyst", "[email protected]"),
    ("Jane", "Senior Python Developer", "[email protected]"),
]

# Use .addBindValue() to insert data
for name, job, email in data:
    insertDataQuery.addBindValue(name)
    insertDataQuery.addBindValue(job)
    insertDataQuery.addBindValue(email)
    insertDataQuery.exec()

I am stuck in assigning the entries of a qtablewidget to data


Solution

  • You can use the following approach:

    # Ignore lazy imports
    import sys
    from typing import *
    
    from PyQt5.QtCore import *
    from PyQt5.QtGui import *
    from PyQt5.QtSql import *
    from PyQt5.QtWidgets import *
    

    First, let's create a function that returns a QTableWidget with the data you provided:

    QTableWidget

    def createTable() -> QTableWidget:
        """Let's create a QTableWidget with the data you provided."""
    
        data = [
            ("Joe", "Senior Web Developer", "[email protected]"),
            ("Lara", "Project Manager", "[email protected]"),
            ("David", "Data Analyst", "[email protected]"),
            ("Jane", "Senior Python Developer", "[email protected]"),
        ]
    
        table = QTableWidget()
    
        table.setRowCount(len(data))
        table.setColumnCount(len(data[0]))
    
        for i, row in enumerate(data):
            for j, val in enumerate(row):
                table.setItem(i, j, QTableWidgetItem(val))
    
        return table
    

    Now we create a function to fetch the data from the table and return it in the same exact format:

    def getData(table: QTableWidget) -> List[Tuple[str]]:
        """Fetch the data from the QTableWidget and return it as `data`."""
    
        data = []
        for row in range(table.rowCount()):
            rowData = []
            for col in range(table.columnCount()):
                rowData.append(table.item(row, col).data(Qt.EditRole))
            data.append(tuple(rowData))
    
        return data
    

    For the db insert part, we can reuse the code you provided:

    def insertData(data: List[Tuple[str]]) -> None:
        """Creating a query for later execution using .prepare()"""
    
        insertDataQuery = QSqlQuery()
        insertDataQuery.prepare(
            """
            INSERT INTO contacts (
                name,
                job,
                email
            )
            VALUES (?, ?, ?)
            """
        )
        # Use .addBindValue() to insert data
        for name, job, email in data:
            insertDataQuery.addBindValue(name)
            insertDataQuery.addBindValue(job)
            insertDataQuery.addBindValue(email)
            insertDataQuery.exec_()
    
        # Note that you need to run `QSqlDatabase().commit()`` if you want the data to be committed in the database.  
    

    Now putting it all together:

    app = QApplication([sys.argv])
    
    # Connect to sample database
    sampleDb = QSqlDatabase.addDatabase("QSQLITE")
    sampleDb.setDatabaseName("sample.sqlite")
    sampleDb.open()
    
    
    # Create table with sample data
    table = createTable()
    
    # Get data from table
    data = getData(table)
    
    # Insert data into the database
    insertData(data)
    
    
    sys.exit(app.exec_())