简体   繁体   中英

Problem with insert and psycopg2

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).

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

那是解决方案

在您的示例中:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM