1

我正在将 postgres 脚本转换为 asyncpg。

我得到“asyncpg.exceptions.PostgresSyntaxError:在“%”处或附近出现语法错误”

我假设我的占位符格式不正确,但我找不到正确格式的示例。

原始工作 psycopg2 代码:

async def commit_trade_postgres(response_data_input):
conn = await psycopg2.connect(
    "dbname='postgres' user='postgres' password = 'postgres123' host='localhost' port= '5432'")
cur = conn.cursor()
cur.execute(
    "CREATE TABLE IF NOT EXISTS trade_{symbol} (time timestamptz NOT NULL ,side text, size float, price float, tick_direction text)".format(**response_data_input))
conn.commit()
cur.execute(
    "SELECT create_hypertable('trade_{symbol}', 'time', if_not_exists => TRUE)".format(**response_data_input))
conn.commit()
cur.execute("INSERT INTO trade_{symbol} (time, side, size, price, tick_direction) VALUES (now(),  %(side)s, %(size)s, %(price)s, %(tick_direction)s)".format(
    **response_data_input), (response_data_input))
conn.commit()
print("commited trade")

我按照文档中提供的示例代码进行的尝试:

async def commit_trade_postgres(response_data_input):
conn = await asyncpg.connect(database='postgres',  user='postgres',  password='postgres123',  host='localhost',  port='5432')
await conn.execute(
    "CREATE TABLE IF NOT EXISTS trade_{symbol} (time timestamptz NOT NULL ,side text, size float, price float, tick_direction text)".format(**response_data_input))
await conn.execute(
    "SELECT create_hypertable('trade_{symbol}', 'time', if_not_exists => TRUE)".format(**response_data_input))
await conn.execute("INSERT INTO trade_{symbol} (time, side, size, price, tick_direction) VALUES (now(),  %(side)s, %(size)s, %(price)s, %(tick_direction)s)".format(
    **response_data_input), (response_data_input))
print("commited trade")

编辑:示例查询,我将“数据”提取为字典。

response_dict_instrument = {'topic': 'instrument.BTCUSD', 'data': [{'symbol': 'BTCUSD', 'mark_price': 12367.29, 'index_price': 12360.1}]}
4

1 回答 1

3

您正在自己格式化查询。你永远不应该那样做。另外我建议您事先为每个传入的符号创建表,不要动态地这样做。

Asyncpg 模板使用$带数字的符号来代替值来为您查询。文档

所以,如果输入是字典,语法应该是这样的。


async def save_input(input):
    # create connection
    conn = ...
    trade_symbol = input['symbol']
    query = "create table if not exists trade_{trade_symbol} ... ".format(trade_symbol=trade_symbol) # your column names go here
    await conn.execute(query)
    query = "SELECT create_hypertable('trade_{trade_symbol} ...".format(trade_symbol=trade_symbol)
    await conn.execute(query)

    # i'm not copyng your exact keys, you should do it yourself
    values = (input['key1'], input['key2'], input['key3'])
    query = "insert into trade_{trade_symbol} (key1, key2, key3) values ($1, $2, $3);".format(trade_symbol=trade_symbol)
    await conn.execute(query, *values)

    await conn.close()

于 2019-07-05T14:28:19.420 回答