【发布时间】:2020-04-17 17:33:03
【问题描述】:
目标:
我有一个包含字符串的列表,其中一些包含单引号(作为字符串本身的一部分);
listOfStr = ['A sample string', "A second string with a ' single quote", 'a third string', ...]
请注意,每个条目不一定使用相同的文本分隔符,有些是单引号,其他(包含单引号作为字符串的一部分)是双引号。
我想使用psycopg2 将我的列表插入为postgresql ARRAY:
import psycopg2
connString = (...) # my DB parameters here.
conn = psycopg2.connect(connString)
curs = conn.cursor()
update_qry = ("""UPDATE "mytable" SET arraycolumn = {listofStr}::varchar[],
timestamp = now() WHERE id = {ID}""".format(listofStr=listofStr,
ID=ID))
curs.execute(update_qry)
问题:
但我得到这个错误:
SyntaxError: syntax error at or near "["
LINE 1: UPDATE "mytable" SET arraycolumn = ['A sample string'...
如果我通过在列表前面添加单词“ARRAY”在 SQL 查询中指定 ARRAY 数据类型:
update_qry = ("""UPDATE "mytable" SET arraycolumn = ARRAY {listofStr}::varchar[],
timestamp = now() WHERE id = {ID}""".format(listofStr=listofStr,
ID=ID))
我得到这个错误:
UndefinedColumn: column "A second string with a ' single quote" does not exist
LINE 1: 'A sample string', "A second string with a '...
我不知道如何解决它。
环境:
- Ubuntu 18.04 64 位 5.0.0-37-generic x86_64 GNU/Linux
- Python 3.6.9(默认,2019 年 11 月 7 日,10:44:02)
- psycopg2 2.7.7
- psycopg2-二进制 2.8.4
- "PostgreSQL 10.10 (Ubuntu 10.10-0ubuntu0.18.04.1) on x86_64-pc-linux-gnu, gcc 编译 (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0, 64-bit" 李>
相关主题:
Postgres/psycopg2 - Inserting array of strings
文档:
【问题讨论】:
标签: arrays python-3.x postgresql psycopg2