views:

27

answers:

1

Hello. I'm a newbie in Python and psycopg2 and have problems with a simple insert.

This is my table:

CREATE TABLE tabla
(
codigo integer NOT NULL DEFAULT nextval('dato_codigo_seq'::regclass),
informacion character(30) NOT NULL,
CONSTRAINT dato_pkey PRIMARY KEY (codigo)
)

The field codigo is a serial.

When I do the sentence:

cursor.execute("INSERT INTO tabla informacion) VALUES (%s)",("abcdef"))

PostgreSQL throws an exception.

I must do

cursor.execute("INSERT INTO tabla (codigo,informacion) VALUES (nextval(%s),%s)",
            ("dato_codigo_seq","abcdef"))

where dato_codigo_seq is the sequence to the field codigo.

My question isL Can I do a sentence like

insert into tabla(informacion)values('asdsa')

and let PostgreSQL handle the treatment of the serial field?

I can do this:

cursor.execute("INSERT INTO tabla informacion) VALUES ("+valor+")")"

but that sentence can be used to attack with a SQL injection.

That's all. Thanks for reading my question, and sorry for my bad english (I speak Spanish).

+1  A: 
cursor.execute("""insert into tabla (informacion) VALUES (%s);""",(asdas,))

that is the solution

to be more explicit, the second argument of execute() must be a tuple, and in Python the trailing comma is mandatory for 1-item tuples.
piro