Evaluate postgres boolean field

donarb donarb at nwlink.com
Fri Jan 4 19:50:50 CET 2013


On Friday, January 4, 2013 10:08:22 AM UTC-8, andyd... at gmail.com wrote:
> Hi,
> 
> I'm hoping for some help on a python script I need to query an api. I'm not a (Python) programmer ordinarily, but do plan to improve!
> 
> Specifically I have a for loop evaluating a database row, which I think I can treat as a list. My [4] is a postgres boolean field, and I'm temporarily stuck on how to evaluate this to determine if I use the values in [1].
> 
> Could I have some advice on what to change? Also do let me know if you can recommend a good beginners python book.
> 
> Data example:
> 
> [13, 'Barbican Station', 'Barbican Station, London Underground Ltd., Aldersgate St, London, EC1A 4JA', '01010000E0E61000008851AB9E9803B9BF5BB6972294C2494000000000000000000000000000000000', True]
> 
> 
> Code:
> 
> #!/usr/bin/python
> import psycopg2
> #note that we have to import the Psycopg2 extras library!
> import psycopg2.extras
> import sys
>  
> def main():
>     conn_string = "host='localhost' dbname='gisdb' user='postgres' password='#########'"
>     # print the connection string we will use to connect
>     print "Connecting to database\n    ->%s" % (conn_string)
>  
>     conn = psycopg2.connect(conn_string)
>  
>     # HERE IS THE IMPORTANT PART, by specifying a name for the cursor
>     # psycopg2 creates a server-side cursor, which prevents all of the
>     # records from being downloaded at once from the server.
>     cursor = conn.cursor('cursor_tube', cursor_factory=psycopg2.extras.DictCursor)
>     cursor.execute('SELECT * FROM tubestations LIMIT 1000')
>  
>     # Because cursor objects are iterable we can just call 'for - in' on
>     # the cursor object and the cursor will automatically advance itself
>     # each iteration.
>     # This loop should run 1000 times, assuming there are at least 1000
>     # records in 'my_table'
>     row_count = 0
>     for row in cursor:
>         row_count += 1
>         if row[4] = True
>             print row[1]
>             #print "row: %s    %s\n" % (row_count, row)
>  
> if __name__ == "__main__":
>     main()
> 
> Thanks!
> 
> 
> Andy

Your code is pretty close to working, you just need to make a couple modifications. You are using the equals sign as an assignment, not a comparison, although the comparison and value are unnecessary since the field's value is either true or false. And you're missing a colon at the end of the condition. Note also that since you are using a DictCursor you can use column names to reference your row's fields, I guessed on the field names, but you should get the idea.


for row in cursor:
    row_count += 1
    if row['active']:
        print row['name']



More information about the Python-list mailing list