Re: Update with function

From: Adrian Klaver <adrian(dot)klaver(at)gmail(dot)com>
To: egbert(dot)bouwman(at)xs4all(dot)nl
Cc: psycopg(at)postgresql(dot)org
Subject: Re: Update with function
Date: 2012-03-30 13:45:35
Message-ID: 4F75B8FF.4080400@gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: psycopg

On 03/30/2012 03:58 AM, egbert wrote:
> Hello,
> I am new to this list, and a fairly unsophisticated user of postgresql
> and psycopg.
>
> I try to update one field in all records of a table.
> The new value is too complicated for a simple expression, so I thought
> about a python function. That function uses another field, recno, from
> each record.
> My question is: how do I pass that second field to the function.
>
> The relevant parts of my script are now:
>
> define makeyear(nummer):
> # ...
> return value
>
> cur.execute("update books set inyear=%s", (makeyear(recno),))
>
> The error message says that recno is not defined.

The parameter list you are passing lives outside the database you are
using so it has no reference to the field recno.

A simple solution that demonstrates one way to do the above:

cur.execute("select recno from some_table")

for row in cur:
recno = cur[0]
cur.execute("update books set inyear=%s", (makeyear(recno),))

> egbert

--
Adrian Klaver
adrian(dot)klaver(at)gmail(dot)com

In response to

Responses

Browse psycopg by date

  From Date Subject
Next Message egbert 2012-03-30 16:02:40 Re: Update with function
Previous Message egbert 2012-03-30 10:58:15 Update with function