简体   繁体   English

使用Python将数据插入Postgresql

[英]Insert data into Postgresql using Python

I am trying to INSERT values in a Postgresql TABLE. 我正在尝试在Postgresql表中INSERT值。 In my python code, there are two returned values a and b from different functions. 在我的python代码中,有两个来自不同函数的返回值ab a and b are tuples . a和b是tuples

like, 喜欢,

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

Database TABLE name is description with six columns. 数据库表名称是具有六列的description 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 ? 但是它显示错误, Error syntax error at or near ","还有其他方法还是应该将其从tuple转换为list

Python doesn't have a (single) standard placeholder value for parameterized queries. 对于参数化查询,Python没有(单个)标准占位符值。 SQLite uses ? SQLite的用途? , but MySQL and Postgresql drivers use %s (for all data types, not just strings): ,但MySQL和Postgresql驱动程序使用%s (对于所有数据类型,而不仅仅是字符串):

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! 就像Blender所说的那样,您只需使用%s but since you got some animal on your data, maybe you can use pg array to store those animal type on the same field! 但是由于您的数据中包含一些动物,因此也许可以使用pg数组将这些动物类型存储在同一字段中!

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') 插入描述值('dog','cat','tree','city','town','road')

BUT, if your animals maybe incr, so the better way is array . 但是,如果您的动物可能会增加,那么更好的方法是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! PG是很好的数据库,有很多type可以使用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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