Re: [pysqlite] How To Insert A Variable Number of Values

"Jeff Peck" <[email protected]> Fri, 30 May 2008 22:28:08 -0500
Newsgroups gmane.comp.python.db.pysqlite.user
Message-ID <[email protected]>
> When I want to save the values entered in the grid, I use this method:
>
>   def OnSave(self, event):
>     stmt = """INSERT or REPLACE into Data (comp, subcomp, var, curr1, curr2,
>                                            curr3, curr4, curr5, curr6,curr7,
>                                            curr8, curr9, curr10, curr11,
>                                            curr12, noact, alt2, alt3, alt4,
>                                            alt5, alt6, alt7, alt8, alt9,
>                                           alt10, alt11, alt12, alt13, alt14,
>                                           alt15, alt16, alt17, alt18) values
>                                           (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,
>                                           ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"""
>
>     for r in range(self.nRows):
>       rowList = []
>       for c in range(self.nCols):
>         rowList.append(self.dataGrid.GetCellValue(r,c))
>       self.appData.cur.execute(stmt)
>     self.appData.cur.commit()
>

Rich,
   I can help you solve this problem. I'd recommend that you create a
method on your grid class that will return a tuple for a given row.
You can probably implement this in a more clever manner, but it would
roughly look like this:

def row_to_tuple(self, row):
    if row >= self.nRows:
        raise RuntimeError, "Row out of range"
    else:
        return tuple(
            self.GetCellValue(row, 0) or None,
            self.GetCellValue(row, 1) or None,
            ......,
            self.GetCellValue(row, 17) or None
        )

Now you can just use the returned tuple as the second parameter to execute:
def OnSave(self, event):
     stmt = """INSERT or REPLACE into Data (comp, subcomp, var, curr1, curr2,
                                            curr3, curr4, curr5, curr6,curr7,
                                            curr8, curr9, curr10, curr11,
                                            curr12, noact, alt2, alt3, alt4,
                                            alt5, alt6, alt7, alt8, alt9,
                                           alt10, alt11, alt12, alt13, alt14,
                                           alt15, alt16, alt17, alt18) values
                                           (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,
                                           ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"""

     for r in range(self.nRows):
       self.appData.cur.execute( stmt, self.dataGrid.row_to_tuple(r) )
     self.appData.cur.commit()


Jeff