Postgres/psycopg2 - Inserting array of strings

前端 未结 4 959
耶瑟儿~
耶瑟儿~ 2020-12-30 02:27

I\'m using Postgres 9 and Python 2.7.2 along with psycopg2 and am trying to insert an array of string values with properly escaped quotation marks. Sample:

m         


        
4条回答
  •  醉话见心
    2020-12-30 02:49

    When you want to insert an array into a postgreSQL DB via SQL you do it like this:

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

    ATTENTION: You need the single quotes to surround the curly braces! So actually you're passing a String/Varchar of a special "array" grammar to the DB

    If I enter your code into a python parser I get something like this:

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

    But PostgreSQL expects something like this:

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

    Check the manual on Arrays: http://www.postgresql.org/docs/9.0/static/arrays.html

    So either you format the String according to the PostgreSQL "array-grammar" by writing a helper function or you use a library which does that for you.

提交回复
热议问题