[Tutor] Handling 'None' (null) values when processing sqlite cursor results

Andre Engels andreengels at gmail.com
Wed Jul 14 09:03:52 CEST 2010

On Wed, Jul 14, 2010 at 6:31 AM, Monte Milanuk <memilanuk at gmail.com> wrote:
> Hello all,
> I'm struggling a bit trying to find the right way to deal with null values
> in my sqlite database when querying it and processing the results in python.
> If my cursor.fetchall() results return the following:
> (104, None, u'Sylvester', None, u'Evans', None, u'527-9210 Proin Av.',
> u'Liberal', u'VT', u'24742', u'1-135-197-1139',
> u'vehicula.Pellentesque at idmollis.edu', u'2010-07-13 22:52:50', u'2010-07-13
> 22:52:50')
> At first I was having fits as str.join() was giving me a 'NoneType error'.
>  I found one way around that, by processing the results so the 'None' values
> got omitted from the list by the time they got to str.join().
> I thought that was the end of that, until I tried working with the returned
> records in another fashion and found that having the 'None' values omitted
> really messed with the list order which I was depending on i.e. list[5]
> could be different fields depending on how many 'None' values had been
> omitted.  And if I didn't omit them, when I printed out the user name in the
> format 'first''middle''last' from the above record, I got
> 'Sylvester''None''Evans' rather than just 'Sylvester''Evans' (i.e. with no
> middle initial).
> So... I guess my question is, is there a good/proper way to handle the
> 'None' values as returned by sqlite from a table that may have some null
> values in individual records?  Basically I want not have the None/Null
> values show up but to keep them as place holders to make sure i get the
> values in the right spots...

It depends a bit on what you want to do with the values. My preference
would be to keep the result of cursor.fetchall(), and instead
re-define the output function(s) that I use (so don't use
str.join(record), but some myjoin(str,record) that I defined). Or,
even better, to define a class for these, create an object of the
class from the fetchall result, and have things like the myjoin before
as class methods or properties.

André Engels, andreengels at gmail.com

More information about the Tutor mailing list