Problem inserting into Postgres (PgSQL) database

Gerhard Häring gh at ghaering.de
Thu Jun 19 12:52:21 CEST 2003


mupeso at arc.sn wrote:
> [...]
> try:~~~
> ~handle=PgSQL.connect(database=configDB, host=configHost, user=configUser, 
> password=configPasswd)
> ~
> except PgSQL.OperationalError, e:
> ~print 'Erreur.'
> 
> sql= "insert into radcheck2 (uid,login,passwd,shell,homedir,domain_name,acc_ex
> pired) values ("+str(uid) +",'"+login+"','"+passwd+"','"+shell+"','"+homedir+"
> ','"+dom_name+"','n')"
> 
> try:
> ~xcursor = handle.cursor()~~~
> ~result= xcursor.execute(sql)~~~~
> ~handle.commit()
>         xcursor.close()
> except PgSQL.OperationalError, e:
> ~print 'ERROR'

First, like Sean said already, without a .commit() you won't see 
anything outside the current transaction, that's connected to the 
database connection you did the insert in.

Second, your style of constructing SQL is a bad one. Use the DB-API way 
of quoting the various datatypes instead:

#v+
sql= """INSERT INTO RADCHECK2
         (UID, LOGIN, PASSWD, SHELL, HOMEDIR, DOMAIN_NAME, ACC_EXPIRED)
          VALUES (%s, %s, %s, %s, %s, %s, %s)""""

cursor.execute(sql, (uid, login, passwd, shell, homedir, dom_name, 'n'))
#v-

The way you're constructing your SQL statement now is a security 
vulnerability if any of the fields can come from an untrusted source.

-- Gerhard





More information about the Python-list mailing list