python-3.xsqlitefor-loopqsqltablemodel

How to use for loop to insert row into QSqltablemodel from a list?


Below is the Database model:

db = QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('book.db')
db.open()

self.model = QtSql.QSqlTableModel(self)
self.model.setTable("card")
self.model.select()

For example:

a = "name"
b = 30
c = "M"
data_row = [a, b, c]

r = self.model.record()
r.setValue("name", "name")
r.setValue("age", 30)
r.setValue("gender", "M")
self.model.insertRecord(-1, r)
self.model.select()

The database have 3 columns that are 'name', 'age','gender'.

My question is how to insert row in to Sqlite table using QSqlTableModel using with for-loop?


Solution

  • I tried below code That's worked for me : Used "for-loop" to count-columns and zip() Function for Parallel Iteration.

    a = "name"
    b = 30
    c = "M"
    data_row = [a, b, c]
    
    columns = []
    for col in range(self.model.columnCount()):
        columns.append(col)
    
    r = self.model.record()
    for col, rec in zip(columns, data_row):
        r.setValue(col, rec)
    
    self.model.insertRecord(-1, r)
    self.model.select()