我使用psycopg3通过以下函数将多行插入到表中:
async def execute_values(self, command_with_placeholders, values) -> None:
placeholders = sql.SQL(', ').join(sql.Placeholder() * len(values[0]))
command = sql.SQL(command_with_placeholders).format(placeholders=placeholders)
async with (await self.conn).cursor() as cursor:
await cursor.executemany(command, values)
字符串
当我包含一个非空的location
时,使用以下参数调用它会失败:
insert_sessions_command = """
INSERT INTO sessions (session_id, start_time, last_activity_time, end_time, ip,
user_agent, country_code, region_code, location)
VALUES ({placeholders});
"""
await sql_db.execute_values(insert_sessions_command, [
('s1', datetime(2023, 1, 1), datetime(2023, 1, 2), None, '1.2.3.4', None,
'NZ', 'NZ-CAN', 'ST_SetSRID(ST_MakePoint(172.6306, 43.5320), 4326)'),
]
型
使用Postgres控制台执行以下操作:
INSERT INTO sessions (session_id, start_time, last_activity_time, end_time, ip,
user_agent, country_code, region_code, location)
VALUES ('s1', '2023-01-01', '2023-01-02', null, '1.2.3.4', null,
'NZ', 'NZ-CAN', ST_SetSRID(ST_MakePoint(172.6306, 43.5320), 4326));
型
所以我猜psycopg代码失败是因为它用引号括住了点,就像下面错误的Postgres命令:
INSERT INTO sessions (session_id, start_time, last_activity_time, end_time, ip,
user_agent, country_code, region_code, location)
VALUES ('s1', '2023-01-01', '2023-01-02', null, '1.2.3.4', null,
'NZ', 'NZ-CAN', 'ST_SetSRID(ST_MakePoint(172.6306, 43.5320), 4326)');
型
在这两种情况下,错误是
parse error - invalid geometry
HINT: "ST" <-- parse error at position 2 within geometry
CONTEXT: unnamed portal parameter $9 = '...'
型
如何使Psycopg代码不将point字符串括在引号中来修复它?
1条答案
按热度按时间f4t66c6m1#
举一个简单的例子来说明我在做什么:
字符串