简体   繁体   中英

Insert data into Postgresql using Python

I am trying to INSERT values in a Postgresql TABLE. In my python code, there are two returned values a and b from different functions. a and b are tuples .

like,

a = ('cat', 'dog', 'tree')
b = ('city', 'town', 'road')

Database TABLE name is description with six columns. I am using

cur.execute("INSERT INTO description VALUES(?,?,?,?,?,?)",(a + b))

I want to append the values within this table. But it is showing error, Error syntax error at or near "," Is there any other way or should I convert it to list from tuple ?

Python doesn't have a (single) standard placeholder value for parameterized queries. SQLite uses ? , but MySQL and Postgresql drivers use %s (for all data types, not just strings):

cur.execute("INSERT INTO description VALUES(%s,%s,%s,%s,%s,%s)", (a + b))

尝试将%s用作有效的格式说明符。

As Blender said it, you just do it with %s will be okay! but since you got some animal on your data, maybe you can use pg array to store those animal type on the same field!

create table description (a char(16), b char(16), c char(16), d char(16), e char(16), f char(16));

you can easy to store your data by:

INSERT INTO description VALUES('dog', 'cat', 'tree', 'city', 'town', 'road')

BUT, if your animals maybe incr, so the better way is array .

create table description2 (animals char(16)[], d char(16), e char(16), f char(16));

and put your data like this.

INSERT INTO description2 VALUES(ARRAY ['dog', 'cat', 'tree'], 'city', 'town', 'road');

and then you can easy to get your data by :

select * from description2;

PG is good database, have many type can be used!

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