psycopg simplest problem

Glauco 00515879256 at fastwebnet.it
Fri Jul 8 11:31:51 EDT 2005


Gerhard Haering wrote:
> On Fri, Jul 08, 2005 at 04:23:50PM +0200, Glauco wrote:
> 
>>[...]
>>My problem is to do a middle layer over pycopg for eliminate type 
>>casting problem in postgres in all direction.
>>
>>i've resolved this doing a C extension in python and manipulating only 
>>string and int in my application.
>>
>>this is my example:
>>import sqlvar
>>
>>sql = """insert into mytable (myint, mytext, maydate)
>>          values
>>          (%d,%s,%s);""" % (sqlvar.number(myvalue1), 
>>sqlvar.text(myvalue2), sqlvar.date(myvalue3) )
>>
>>all problem concerning quoting, " ' -> ''", null, None, 0, empty string 
>>is solved by the sqlvar lib. [...]
> 
> 
> Instead of quoting Python values yourself appropriately for each type,
> just let the DB-API module do its work. Use parametrized queries and
> then supply the arguments to the query:
> 
> cur = con.cursor()
> intVal = 42
> textVal = "Jason's house"
> dateVal = datetime.date(2005, 7, 8)
> cur.execute("""
>     insert into mytable(myint, mytext, mydate)
>     values (%s, %s, %s)
>     """, (intval, textVal, dateVal))
> 
> The execute(many) method has an optional second parameter, which is a
> tuple of values for your parametrized query.
> 
> There are different styles to parametrize queries among the various
> DB-API modules. psycopg uses the pyformat one, where you just use %s as
> placeholders.
> 
> It will happily quote all Python values of types int, str, date, float,
> etc.  for you. It's also possible to teach it how to quote other custom
> data types, but you'll normally not need this.
> 
> HTH,
> 
> -- Gerhard

Gerhard thank you very much, this example explain me some idea, but 
anyway don't resolve the core question.
In you example when dateVal is a None or textVal is none.
argument x must be DateTime, not None.
so i must manipulate for the empty string or None cases



Glauco
-- 



More information about the Python-list mailing list