| title | Cursor |
|---|
Cursor objects represents server-side Cursor in the PostgreSQL. PostgreSQL docs.
::: important
Cursor always lives inside a transaction. If you don't begin transaction explicitly, it will be opened anyway.
:::
querystring: specify query for cursor.parameters: parameters for the querystring. DefaultNonefetch_number: default fetch number. It is used infetch()method and in async iterator.
Cursor can be used in different ways.
::: tabs @tab Pre-Initialization
from psqlpy import ConnectionPool, QueryResult
async def main() -> None:
db_pool = ConnectionPool()
connection = await db_pool.connection()
cursor = connection.cursor(
querystring="SELECT * FROM users WHERE id > $1",
parameters=[100],
fetch_number=10,
)
await cursor.start()@tab Post-Initialization
from psqlpy import ConnectionPool, QueryResult
async def main() -> None:
db_pool = ConnectionPool()
connection = await db_pool.connection()
cursor = connection.cursor()
await cursor.execute(
querystring="SELECT * FROM users WHERE id > $1",
parameters=[100],
)
result: QueryResult = await cursor.fetchone()@tab Async Context Manager
from psqlpy import ConnectionPool, QueryResult
async def main() -> None:
db_pool = ConnectionPool()
connection = await db_pool.connection()
async with connection.cursor(
querystring="SELECT * FROM users WHERE id > $1",
parameters=[100],
array_size=10,
) as cursor:
result: QueryResult = await cursor.fetchone()@tab Async Iterator
from psqlpy import ConnectionPool, QueryResult
async def main() -> None:
db_pool = ConnectionPool()
connection = await db_pool.connection()
cursor = connection.cursor(
querystring="SELECT * FROM users WHERE id > $1",
parameters=[100],
fetch_number=10,
)
await cursor.start()
async for result in cursor:
print(result):::
array_size: get and set attribute. Used in async iterator andfetch_manymethod.
Declare (create) cursor.
async def main() -> None:
await cursor.start()Close the cursor
async def main() -> None:
await cursor.close()Initialize cursor and make it ready for fetching.
::: important
If you initialized cursor with start method or via context manager, you don't have to use this method.
:::
querystring: specify query for cursor.parameters: parameters for the querystring. DefaultNone
async def main() -> None:
await cursor.execute(
querystring="SELECT * FROM users WHERE id > $1",
parameters=[100],
)
result: QueryResult = await cursor.fetchone()Fetch one result from the cursor.
async def main() -> None:
result: QueryResult = await cursor.fetchone()Fetch N results from the cursor. Default is array_size.
size: number of records to fetch.
async def main() -> None:
result: QueryResult = await cursor.fetchmany(size=10)Fetch all results from the cursor.
async def main() -> None:
result: QueryResult = await cursor.fetchall()