Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python PostgreSQL libraries connect applications to a PostgreSQL database, run SQL, and return rows. A driver either calls libpq, the PostgreSQL C client library, or speaks the PostgreSQL wire protocol directly. These libraries let web apps and backend services read and write relational data from Python.
Popularity
psycopg2 has the most monthly downloads in this comparison, at 239.0M.
@async_unsafe
def get_new_connection(self, conn_params):
# self.isolation_level must be set: # - after connecting to the database in order to obtain the database's # default when no value is explicitly specified in options. # - before calling _set_autocommit() because if autocommit is on, that # will set connection.isolation_level to ISOLATION_LEVEL_AUTOCOMMIT. options = self.settings_dict["OPTIONS"]
set_isolation_level = False
try:
isolation_level_value = options["isolation_level"]
except KeyError:
self.isolation_level = IsolationLevel.READ_COMMITTED
else:
# Set the isolation level to the value from OPTIONS. try:
self.isolation_level = IsolationLevel(isolation_level_value)
set_isolation_level = True
except ValueError:
raise ImproperlyConfigured(
f"Invalid transaction isolation level {isolation_level_value} "
f"specified. Use one of the psycopg.IsolationLevel values."
)
if self.pool:
# If nothing else has opened the pool, open it now. self.pool.open()
connection = self.pool.getconn()
else:
connection = self.Database.connect(**conn_params)
if set_isolation_level:
connection.isolation_level = self.isolation_level
if not is_psycopg3:
# Register dummy loads() to avoid a round trip from psycopg2's # decode to json.dumps() to json.loads(), when using a custom # decoder in JSONField. psycopg2.extras.register_default_jsonb(
conn_or_curs=connection, loads=lambda x: x
)
return connection
Psycopg
Provides PostgreSQL connections, cursors, and query execution for Python.
Downloads / mo
216.8M
Stars
2.5K
Last release
3.3.9
License
LGPL-3.0-only
Strengths
Offers sync and async interfaces.Use similar connection and cursor patterns in synchronous and asynchronous code.
Streams PostgreSQL COPY data.Read or write COPY data through a managed Copy object.
Limitations
Pooling needs another package.Install psycopg_pool or the pool extra to use connection pools.
Windows async needs another loop.Select an event loop compatible with Psycopg asynchronous connections.
def execute_normal_sql(self, split_sql):
"""Returns tuple (title, rows, headers, status)"""
_logger.debug("Regular sql statement. sql: %r", split_sql)
title = ""
def handle_notices(n):
nonlocal title
title = f"{title}"
if n.message_primary is not None:
title = f"{title}\n{n.message_primary}"
if n.message_detail is not None:
title = f"{title}\n{n.message_detail}"
self.conn.add_notice_handler(handle_notices)
if self.is_virtual_database() and "show help" in split_sql.lower():
# see https://github.com/psycopg/psycopg/issues/303 # special case "show help" in pgbouncer res = self.conn.pgconn.exec_(split_sql.encode())
return title, None, None, res.command_status.decode()
cur = self.conn.cursor()
cur.execute(split_sql)
# cur.description will be None for operations that do not return # rows. if cur.description:
headers = [x[0] for x in cur.description]
return title, cur, headers, cur.statusmessage
elif cur.protocol_error:
_logger.debug("Protocol error, unsupported command.")
return title, None, None, cur.protocol_message
else:
_logger.debug("No rows in result.")
return title, None, None, cur.statusmessage
asyncpg
Implements PostgreSQL’s protocol for Python asyncio applications.
Downloads / mo
145.4M
Stars
8.1K
Last release
0.32.0
License
Apache-2.0
Strengths
Includes an asynchronous connection pool.Acquire, use, and return connections through the built-in pool.
Converts PostgreSQL types automatically.Receive arrays, composite values, and other PostgreSQL types as Python values.
Limitations
Prepared objects expire after release.Recreate statement and cursor objects when acquiring a connection again.
import adbc_driver_postgresql.dbapi as dbapi
with dbapi.connect("postgresql://postgres@localhost/test") as conn:
with conn.cursor() as cur:
cur.execute("SELECT 1")
print(cur.fetchone())
def _open_adbc_connection(connection_uri: str) -> Any:
driver_name = _get_adbc_driver_name_from_uri(connection_uri)
module_name = _get_adbc_module_name_from_uri(connection_uri)
# some backends require the driver name to be stripped from the URI if driver_name in ("duckdb", "snowflake", "sqlite"):
connection_uri = re.sub(f"^{driver_name}:/{{,3}}", "", connection_uri)
try:
adbc_driver = _import_optional_adbc_driver(module_name)
except ModuleUpgradeRequiredError:
raise
except ModuleNotFoundError as err:
if (found := _find_installed_adbc_driver_for(driver_name, err)) is None:
raise
# load the driver library through the generic driver manager dbapi = import_module("adbc_driver_manager.dbapi")
library, entrypoint = found
return dbapi.connect(
driver=library,
entrypoint=entrypoint,
db_kwargs=_adbc_db_kwargs(driver_name, connection_uri),
)
return adbc_driver.connect(connection_uri)
import asyncio
import aiopg
async def main():
async with aiopg.create_pool("dbname=test user=postgres host=localhost") as pool:
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute("SELECT 1")
print(await cur.fetchone())
asyncio.run(main())
def makeConnection(self):
try:
if self.driver in ('odbc', 'pyodbc', 'pypyodbc'):
self.debugWriter.write(
"ODBC connect string: " + self.odbc_conn_str)
conn = self.module.connect(self.odbc_conn_str)
elif self.use_dsn:
conn = self.module.connect(self.dsn)
else:
conn = self.module.connect(**self.dsn_dict)
except self.module.OperationalError as e:
raise dberrors.OperationalError(
ErrorMessage(e, "used connection string %r" % self.dsn))
# For printDebug in _executeRetry self._connectionNumbers[id(conn)] = self._connectionCount
if self.autoCommit:
self._setAutoCommit(conn, 1)
c = conn.cursor()
if self.schema:
self._executeRetry(conn, c, "SET search_path TO " + self.schema)
dbEncoding = self.dbEncoding
if dbEncoding:
if self.driver in ('odbc', 'pyodbc'):
conn.setdecoding(self.module.SQL_CHAR, encoding=dbEncoding)
conn.setdecoding(self.module.SQL_WCHAR, encoding=dbEncoding)
if PY2:
conn.setencoding(str, encoding=dbEncoding)
conn.setencoding(unicode, encoding=dbEncoding) # noqa
else:
conn.setencoding(encoding=dbEncoding)
self._executeRetry(conn, c,
"SET client_encoding TO '%s'" % dbEncoding)
c.close()
return conn
FAQ
Psycopg suits new projects and offers synchronous and native async interfaces. asyncpg suits asyncio services that want a dedicated protocol client and pool. pg8000 suits environments that cannot install libpq.
Psycopg is the current generation of the adapter. Its publisher recommends it for new projects and keeps psycopg2 for existing integrations.
asyncpg is an asyncio PostgreSQL driver with its own protocol client and connection pool. It does not offer a synchronous DB-API interface.
pg8000 is a pure Python PostgreSQL driver with both DB-API and native query interfaces. It does not depend on libpq.
For coding agents
Found your PostgreSQL library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.