Postgres/psycopg2-插入字符串数组

2024-05-09 13:16:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Postgres 9和Python 2.7.2以及psycopg2,并试图插入一个字符串值数组,其中包含正确转义的引号。样品:

metadata = {"Name": "Guest", "Details": "['One', 'Two', 'Three']"}

cur.execute("insert into meta values ('%s');" % metadata)

这引发了一个例外:

psycopg2.ProgrammingError: syntax error at or near "One"
LINE 1: "Details": "['One...
                      ^

我也试过用Postgres'E和反斜杠一起逃脱,但还没有找到正确的组合。思想?


Tags: 字符串nameexecute样品postgres数组detailsone
3条回答
def lst2pgarr(alist):
    return '{' + ','.join(alist) + '}'

pyarray = ['pippo', 'minni', 1, 2]

conn = psycopg2.connection (  HERE PUT YOUR CONNECTION STRING  )
c = conn.cursor()

c.execute('select ... where pgarray_attr = %r' % (lst2pgarr(pyarray))
c.execute('insert into tab(pgarray_attr) values (%r)' % (lst2pgarr(pyarray))

你必须让psycopg为你绑定参数:不要试图自己引用它们。

Psycopg自动将python字符串列表转换为postgres数组。检查http://initd.org/psycopg/docs/usage.html

当您想通过SQL将数组插入postgreSQL数据库时,您可以这样做:

INSERT INTO tablename VALUES ('{value1,value2,value3}');

注意:需要用单引号将大括号括起来!所以实际上,您将一个特殊“array”语法的String/Varchar传递给DB

如果我将您的代码输入到python解析器中,会得到如下结果:

'{'Name': 'Guest', 'Details': "['One', 'Two', 'Three']"}'

但是PostgreSQL希望这样:

'{"Name","Guest","Details",{"One","Two","Three"}}'

查看数组手册:http://www.postgresql.org/docs/9.0/static/arrays.html

因此,要么通过编写一个helper函数,根据PostgreSQL的“数组语法”格式化字符串,要么使用一个库来实现这一点。

相关问题 更多 >