我正在尝试构建一段代码,使用asyncpg
添加内容到我的postgres数据库中的表,定义如下:
CREATE TABLE my_table (
id SERIAL NOT NULL UNIQUE,
nested_field varchar(100) NOT NULL UNIQUE,
subfields varchar(100)[]
);
对于我的POV,困难的部分是将内容保存到postgres数组变量中。
我构建的这段代码如下:try:
await connection.execute(query, thing_string, subfields_string)
return None
except (Exception, asyncpg.UniqueViolationError) as integrError:
# some other action
except (Exception, asyncpg.ConnectionFailureError) as error:
# some other action
finally:
# some other action
query
它运行在哪里定义为:
query = """
INSERT INTO my_table(thing, subfields)
VALUES($1,$2);
"""
和args*
(这里是关于asyncpg函数connection.execute
的args*
参数的文档)
作为$1和$2 ,将被放入字符串的
thing_string
,定义为thing_string = "something"
和
行得到subfields_string
,通过运行
subfields_string = from_list_to_stringified_set(list_of_subfields)
,
list_of_subfields = ["one, two, three"]
和函数定义如下:
def from_list_to_stringified_set(list_of_subfields):
"""
Given a list of subfields
[ "subfield1", "subfield2", "subfield3" ]
it returns
'{ "subfield1", "subfield2", "subfield3" }'
"""
subfields_string = ""
for subfield in list_of_subfields:
subfields_string = subfields_string + '", "' + subfield
subfields_string = '{' + subfields_string[3:] + '"}'
return subfields_string
使subfields_string
的值结果为'{"one, two, three"}'
(这个结果由我的代码正确实现)。
为了正确工作,在数据库上运行的查询应该是:
# desired result INSERT INTO my_table(title, subfields) VALUES('something','{"one", "two", "three"}');
然而,当我尝试运行脚本时,我得到
asyncpg.exceptions.DataError: invalid input for query argument $2: '{"one", "two", "three"}' (a sized iterable container expected (got type 'str'))
所以connection.execute(...)
不接受我的第二个参数,subfields_string
,值为'{"one, two, three"}'
,因为显然它想要一个可迭代对象而不是字符串。
但是为什么呢?
作为args*
的一部分,我传递给connection.execute(...)
的其他参数也是字符串,那么为什么第二个参数被拒绝而第一个参数被接受?
我怎样才能改变我的代码,以获得# desired result
?
使用字符串列表作为参数
query = """
INSERT INTO my_table(nested_field, subfields)
VALUES($1,$2);
"""
thing_string = 'something'
subfields_string = ["one", "two", "three"]
await connection.execute(query, thing_string, subfields_string)
列subfields
是一个varchar数组。它对应的Python类型是一个列表,如文档