2010-05-25 149 views
2

我是Python和psycopg2中的新手,并且存在插入简单问题。插入问题和psycopg2

这是我的表:

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

领域codigo是串行。

当我做了一句:

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

的PostgreSQL抛出一个异常。

我必须做

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

其中dato_codigo_seq是序列到外地codigo

我的问题ISL我可以这样做

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

,让PostgreSQL的处理串行现场治疗的句子?

我可以这样做:

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

但这句话可以使用SQL注入攻击。

就是这样。感谢您阅读我的问题,并对我的英语不好(我会说西班牙语)感到抱歉。

+0

Bienvenidos一个StackOverflow上。 – bernie 2010-05-26 03:26:34

+0

也有类似的问题。然而,'''cursor.execute(“INSERT INTO tabla informacion)VALUES(”+ valor +“)”)“'''type line没有保存在数据库中,它只是增加了我的db序列号 – 2011-10-18 00:28:51

回答

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

这是解决

+3

显式的,execute()的第二个参数必须是一个元组,而在Python中,尾部逗号对于1项元组是强制的。 – piro 2010-07-02 16:42:22

0
在你的榜样

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