.. note:: You can use :ref:`with conn.cursor(): ...<usage>`
to close the cursor automatically when the block is exited.
+ .. automethod:: execute(query: Query, params: Optional[Args]=None) -> Cursor
+
+ :param query: The query to execute
+ :type query: `!str`, `!bytes`, or `sql.Composable`
+ :param params: The parameters to pass to the query, if any
+ :type params: Sequence or Mapping
+
+ The cursor is what returned calling `cursor()` without parameters. See
+ :ref:`query-parameters` for all the details about executing queries.
.. rubric:: Transaction management methods
automatically when the block is exited, but be careful about
the async quirkness: see :ref:`async-with` for details.
+ .. automethod:: execute(query: Query, params: Optional[Args]=None) -> AsyncCursor
.. automethod:: commit
.. automethod:: rollback
from . import encodings
from .pq import TransactionStatus, ExecStatus, Format
from .sql import Composable
-from .proto import DumpersMap, LoadersMap, PQGen, PQGenConn, RV, Query
+from .proto import DumpersMap, LoadersMap, PQGen, PQGenConn, RV, Query, Params
from .waiting import wait, wait_async
from .conninfo import make_conninfo
from .generators import notifies
self._exec_command(b"begin")
+ def execute(
+ self, query: Query, params: Optional[Params] = None
+ ) -> "Cursor":
+ """Execute a query and return a cursor to read its results."""
+ cur = self.cursor()
+ return cur.execute(query, params)
+
def commit(self) -> None:
"""Commit any pending transaction to the database."""
with self.lock:
await self._exec_command(b"begin")
+ async def execute(
+ self, query: Query, params: Optional[Params] = None
+ ) -> "AsyncCursor":
+ cur = await self.cursor()
+ return await cur.execute(query, params)
+
async def commit(self) -> None:
async with self.lock:
if self._savepoints:
with pytest.raises(ValueError):
conn.remove_notify_handler(cb1)
+
+
+def test_execute(conn):
+ cur = conn.execute("select %s, %s", [10, 20])
+ assert cur.fetchone() == (10, 20)
+
+ cur = conn.execute("select %(a)s, %(b)s", {"a": 11, "b": 21})
+ assert cur.fetchone() == (11, 21)
+
+ cur = conn.execute("select 12, 22")
+ assert cur.fetchone() == (12, 22)
with pytest.raises(ValueError):
aconn.remove_notify_handler(cb1)
+
+
+async def test_execute(aconn):
+ cur = await aconn.execute("select %s, %s", [10, 20])
+ assert await cur.fetchone() == (10, 20)
+
+ cur = await aconn.execute("select %(a)s, %(b)s", {"a": 11, "b": 21})
+ assert await cur.fetchone() == (11, 21)
+
+ cur = await aconn.execute("select 12, 22")
+ assert await cur.fetchone() == (12, 22)