Python 使用 QSqlDatabase 将 Qtable Widget 中的数据插入到 Ms Access 中

Python Insert Data from Qtable Widget into Ms Access with QSqlDatabase

这是我目前拥有的:

 def save_invoice(self):

    con = QSqlDatabase.addDatabase("QODBC")
    con.setDatabaseName("C:/Users/Egon/Documents/Invoice/Invoice.accdb")

    # Open the connection
    con.open()        
    # Creating a query for later execution using .prepare()
    insertDataQuery = QSqlQuery()
    insertDataQuery.prepare(
        """
        INSERT INTO Test01 (
            Quantity,
            ProductId,
            Description,
            Price,
            Tax,
            NetTotal,
            GrossTotal
        )
        VALUES (?, ?, ?, ?, ?, ?, ?)
        """
    )
    
    data = getData(self.tableWidgetInvoiceItem)     

    for Quantity, ProductId, Description, Price, Tax, NetTotal, GrossTotal in data:
        insertDataQuery.addBindValue(Quantity)
        insertDataQuery.addBindValue(ProductId)
        insertDataQuery.addBindValue(Description)
        insertDataQuery.addBindValue(Price)
        insertDataQuery.addBindValue(Tax)
        insertDataQuery.addBindValue(NetTotal)
        insertDataQuery.addBindValue(GrossTotal)
        insertDataQuery.exec_()     
        print(insertDataQuery.lastError().text())
        con.commit()

从 QTableWidget 获取数据并return它作为data

def getData(table: QTableWidget) -> List[Tuple[str]]:


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    

没有显示错误消息,但也没有记录插入数据库。我该如何解决?

尝试使用 QSqlDatabase.commit() 而不是 con.commit()