postgresql 使用Psycopg3插入多行PostGIS点

w1e3prcc  于 2024-01-07  发布在  PostgreSQL
关注(0)|答案(1)|浏览(109)

我使用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字符串括在引号中来修复它?

f4t66c6m

f4t66c6m1#

举一个简单的例子来说明我在做什么:

import psycopg
from psycopg import sql

con = psycopg.connect('dbname=test host=localhost user=postgres')
cur = con.cursor()

sql_str = sql.SQL('select {round}({random}()::numeric, %s)')
cur.execute(sql_str.format(round=sql.Identifier('round'), random=sql.Identifier('random')), [3]).fetchone()
(Decimal('0.357'),)

cur.execute(sql_str.format(round=sql.Identifier('round'), random=sql.Identifier('random')), [2]).fetchone()
(Decimal('0.50'),)

字符串

相关问题