Python Data Presistence – Row Object

Python Data Presistence – Row Object

By default, each row in the query result set is a tuple of values belonging to the column list in the SELECT statement. In the above example, the row object returns a tuple.

Example

>>> row=cur. f etchone ( )
> > > row
(2, 'TV', 40000)
>>> type(row)
<class 'tuple'>

The order of columns in the tuple cannot be ascertained from the object itself. The connection object has a useful ‘row_£actory’ property with which row in the result set can be converted into some meaningful representation. This can be done either by assigning a row factory to a user-defined function that will return a custom object or by setting it to the constructor of the Row class.

Row class has been defined in the sqlite3 module, whose primary purpose is to be used as a row factory. As a result, the row of the result set is returned as a Row object. Row class defines a keys () method that returns column names used in the SELECT statement. Values are accessible using the index as well as by name.

Example

>>> r=cur.fetchone( )
>>> type(r)
<class 'sqlite3.Row'>
>>> r.keysO
t'ProductID', 'Name', 'Price']
>>> fields=r .keys ( )
>>> r[1]
'TV'
> > > r['name']
'TV'
>>> for nm in fields:
print (nm, r[nm])
ProductID 2
Name TV
Price 40000