Search code examples
postgresqlcursorprepared-statementpython-3.6asyncpg

How to add a collection(list etc) param in prepared statement cursor


So I am using asyncpg prepared statement and executing query. I am passing positional arguments in my query.

Currently, I pass stmt.cursor(params[0], params[1]) but what if I don't know how many arguments are being passed so wanted to pass a list or something to this method. How can I achieve this in this case?

My current code:

async def execute_ps(dsn):
    conn = await asyncpg.connect(dsn)

    sql_query = """select * from table1 where id = $1 and name=$2"""
    params = [var1, var2]
    stmt = await conn.prepare(sql_query)

    result = []

    try:
        async with conn.transaction():
            async for record in stmt.cursor(params[0], params[1]): # want to pass list here
                print(record)
                result.append(record)
    except Exception as e:
        print("exception: {}", e)

    if conn is None:
        await conn.close()

    return result

Solution

  • My bad. I found out it has to be using *. I am new to python so didn't get it at the first thought!

    async for record in stmt.cursor(*params)