# Python PostgreSQL libraries

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

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [psycopg2](#psycopg-binary) | 239.0M | 3.7K | Sep 2026 | LGPL with exceptions |
| [Psycopg](#psycopg) | 216.8M | 2.5K | Nov 2026 | LGPL-3.0-only |
| [asyncpg](#asyncpg) | 145.4M | 8.1K | Oct 2026 | Apache-2.0 |
| [pg8000](#pg) | 55.0M | Not on GitHub | Oct 2026 | BSD-3-Clause |
| [ConnectorX](#connectorx) | 1.6M | 2.7K | Sep 2026 | MIT |
| [ADBC PostgreSQL](#adbc-driver-postgresql) | 1.2M | 639 | Oct 2026 | Apache-2.0 |
| [aiopg](#aiopg) | 685.1K | 1.4K | Oct 2022 | BSD |
| [PyGreSQL](#pygresql) | 339.5K | 48 | Jan 2026 | PostgreSQL |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[psycopg2](#psycopg-binary) has the most monthly downloads in this comparison, at 239.0M.

## Capabilities

| Library | Async query API | Sync query API |
| --- | --- | --- |
| [psycopg2](#psycopg-binary) | No | Yes |
| [Psycopg](#psycopg) | Yes | Yes |
| [asyncpg](#asyncpg) | Yes | No |
| [pg8000](#pg) | No | Yes |
| [ConnectorX](#connectorx) | No | Yes |
| [ADBC PostgreSQL](#adbc-driver-postgresql) | No | Yes |
| [aiopg](#aiopg) | Yes | No |
| [PyGreSQL](#pygresql) | No | Yes |

## Libraries

### psycopg2

[GitHub](https://github.com/psycopg/psycopg2) · [PyPI](https://pypi.org/project/psycopg2-binary) · [Docs](https://pypi.org/pypi/psycopg2-binary/2.9.13/json)

Packages the Psycopg 2 PostgreSQL adapter as a binary wheel.

- Downloads / mo: 239.0M
- Stars: 3.7K
- Last release: 2.9.13
- License: LGPL with exceptions
- Capabilities: [From the psycopg2 docs](https://pypi.org/pypi/psycopg2-binary/2.9.13/json)

**Strengths**

- **Wraps PostgreSQL’s libpq client.** Use the established libpq-backed PostgreSQL adapter.
- **Includes threaded connection pooling.** Use ThreadedConnectionPool when application threads need pooled database connections.

**Watch out for**

- **Binary dependencies update separately.** Upgrade the package to update its bundled libpq and libssl libraries.
- **Async mode disables COPY.** Use a synchronous connection for Psycopg COPY operations.

```sh
python3 -m pip install psycopg2-binary
```

**django/django** (91.8K stars)

[django/django](https://github.com/django/django) 

```python
@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

```

[django/db/backends/postgresql/base.py](https://github.com/django/django/blob/f24f38c6b2825f15628c07bf2892f1664eed9361/django/db/backends/postgresql/base.py#L316-L354) · [More projects using psycopg2 →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20psycopg2-binary%20for%20PostgreSQL%20query%20execution%2C%20transaction%20handling%2C%20connection%20setup%20and%20COPY%20streaming&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import psycopg2
conn = psycopg2.connect("dbname=test user=postgres")
cur = conn.cursor()
cur.execute("SELECT 1")
print(cur.fetchone())
cur.close()
conn.close()

```

From [usage.html](https://www.psycopg.org/docs/usage.html)

### Psycopg

[GitHub](https://github.com/psycopg/psycopg) · [PyPI](https://pypi.org/project/psycopg) · [Docs](https://pypi.org/pypi/psycopg/3.3.9/json)

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
- Capabilities: [From the Psycopg docs](https://pypi.org/pypi/psycopg/3.3.9/json)

**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.

**Watch out for**

- **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.

```sh
python3 -m pip install "psycopg[binary]"
```

**dbcli/pgcli** (13.4K stars)

[dbcli/pgcli](https://github.com/dbcli/pgcli) 

```python
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

```

[pgcli/pgexecute.py](https://github.com/dbcli/pgcli/blob/dc9ce9447e0fc005a347b75b7eb5d541e282b1c1/pgcli/pgexecute.py#L451-L486) · [More projects using Psycopg →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20psycopg%20for%20PostgreSQL%20query%20execution%2C%20transaction%20handling%2C%20connection%20setup%20and%20COPY%20streaming&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import psycopg
with psycopg.connect("dbname=test user=postgres") as conn:
    print(conn.execute("SELECT 1").fetchone())

```

From [usage.html](https://www.psycopg.org/psycopg3/docs/basic/usage.html)

### asyncpg

[GitHub](https://github.com/MagicStack/asyncpg) · [PyPI](https://pypi.org/project/asyncpg) · [Docs](https://pypi.org/pypi/asyncpg/0.32.0/json)

Implements PostgreSQL’s protocol for Python asyncio applications.

- Downloads / mo: 145.4M
- Stars: 8.1K
- Last release: 0.32.0
- License: Apache-2.0
- Capabilities: [From the asyncpg docs](https://pypi.org/pypi/asyncpg/0.32.0/json)

**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.

**Watch out for**

- **Prepared objects expire after release.** Recreate statement and cursor objects when acquiring a connection again.

```sh
python3 -m pip install asyncpg
```

**encode/databases** (4.0K stars)

[encode/databases](https://github.com/encode/databases) 

```python
async def start(
    self, is_root: bool, extra_options: typing.Dict[typing.Any, typing.Any]
) -> None:
    assert self._connection._connection is not None, "Connection is not acquired"
    self._transaction = self._connection._connection.transaction(**extra_options)
    await self._transaction.start()

```

[databases/backends/postgres.py](https://github.com/encode/databases/blob/ae3fb16f40201d9ed0ed31bea31a289127169568/databases/backends/postgres.py#L205-L210) · [More projects using asyncpg →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20asyncpg%20for%20PostgreSQL%20query%20execution%2C%20transaction%20handling%2C%20connection%20setup%20and%20COPY%20streaming&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import asyncio
import asyncpg
async def main():
    conn = await asyncpg.connect("postgresql://postgres@localhost/test")
    try:
        print(await conn.fetchval("SELECT 1"))
    finally:
        await conn.close()
asyncio.run(main())

```

From [README.rst](https://magicstack.github.io/asyncpg/current/api/index.html)

### pg8000

[PyPI](https://pypi.org/project/pg8000) · [Docs](https://pypi.org/pypi/pg8000/1.31.6/json)

Provides a pure-Python PostgreSQL driver that implements DB-API.

- Downloads / mo: 55.0M
- Last release: 1.31.6
- License: BSD-3-Clause
- Capabilities: [From the pg8000 docs](https://pypi.org/pypi/pg8000/1.31.6/json)

**Strengths**

- **Runs as a pure-Python driver.** Use PostgreSQL without installing a C client-library extension.
- **Offers native and DB-API interfaces.** Choose the native interface or the standardized DB-API interface.

**Watch out for**

- **Connections belong to one thread.** Create separate connections for concurrent work in different threads.

```sh
python3 -m pip install pg8000
```

**sqlalchemy/sqlalchemy** (12.3K stars)

[sqlalchemy/sqlalchemy](https://github.com/sqlalchemy/sqlalchemy) 

```python
def set_isolation_level(self, dbapi_connection, level):
    level = level.replace("_", " ")

    if level == "AUTOCOMMIT":
        dbapi_connection.autocommit = True
    else:
        dbapi_connection.autocommit = False
        cursor = dbapi_connection.cursor()
        cursor.execute(
            "SET SESSION CHARACTERISTICS AS TRANSACTION "
            f"ISOLATION LEVEL {level}"
        )
        cursor.execute("COMMIT")
        cursor.close()

```

[lib/sqlalchemy/dialects/postgresql/pg8000.py](https://github.com/sqlalchemy/sqlalchemy/blob/fe8e67751891de18ba27171bbc8aa23b28bb8348/lib/sqlalchemy/dialects/postgresql/pg8000.py#L517-L530) · [More projects using pg8000 →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20pg8000%20for%20PostgreSQL%20query%20execution%2C%20transaction%20handling%2C%20connection%20setup%20and%20COPY%20streaming&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import pg8000.dbapi
conn = pg8000.dbapi.connect(user="postgres", database="test")
cur = conn.cursor()
cur.execute("SELECT 1")
print(cur.fetchone())
cur.close()
conn.close()

```

From [README.md](https://pypi.org/pypi/pg8000/1.31.6/json)

### ConnectorX

[GitHub](https://github.com/sfu-db/connector-x) · [PyPI](https://pypi.org/project/connectorx)

Loads data from databases into DataFrames from Rust and Python.

- Downloads / mo: 1.6M
- Stars: 2.7K
- Last release: 0.4.6
- License: MIT
- Capabilities: [From the ConnectorX docs](https://github.com/sfu-db/connector-x)

```sh
python3 -m pip install connectorx pandas
```

**pola-rs/polars** (40.4K stars)

[pola-rs/polars](https://github.com/pola-rs/polars) 

```python
def _read_sql_connectorx(
    query: str | list[str],
    connection_uri: str,
    partition_on: str | None = None,
    partition_range: tuple[int, int] | None = None,
    partition_num: int | None = None,
    protocol: str | None = None,
    schema_overrides: SchemaDict | None = None,
    pre_execution_query: str | list[str] | None = None,
) -> DataFrame:
    cx = import_optional("connectorx")

    if parse_version(cx.__version__) < (0, 4, 2):
        if pre_execution_query:
            msg = "'pre_execution_query' is only supported in connectorx version 0.4.2 or later"
            raise ValueError(msg)
        return_type = "arrow2"
        pre_execution_args = {}
    else:
        return_type = "arrow"
        pre_execution_args = {"pre_execution_query": pre_execution_query}

    try:
        tbl = cx.read_sql(
            conn=connection_uri,
            query=query,
            return_type=return_type,
            partition_on=partition_on,
            partition_range=partition_range,
            partition_num=partition_num,
            protocol=protocol,
            **pre_execution_args,
        )
    except BaseException as err:
        # basic sanitisation of /user:pass/ credentials exposed in connectorx errs
        errmsg = re.sub("://[^:]+:[^:]+@", "://***:***@", str(err))
        raise type(err)(errmsg) from err

    return from_arrow(tbl, schema_overrides=schema_overrides)  # type: ignore[return-value]

```

[py-polars/src/polars/io/database/_utils.py](https://github.com/pola-rs/polars/blob/c5f0f25b2ed6498dd47d3ec619ef3a1a90c0788b/py-polars/src/polars/io/database/_utils.py#L29-L67) · [More projects using ConnectorX →](https://dashboard.exa.ai/playground/search?q=connectorx%20GitHub%20projects)

**Quickstart**

```python
import connectorx as cx
cx.read_sql("postgresql://username:password@server:port/database", "SELECT * FROM lineitem")

```

From [README.md](https://github.com/sfu-db/connector-x)

### ADBC PostgreSQL

[GitHub](https://github.com/apache/arrow-adbc) · [PyPI](https://pypi.org/project/adbc-driver-postgresql) · [Docs](https://arrow.apache.org/adbc/current/driver/postgresql.html)

Connects to PostgreSQL through an ADBC driver built on libpq.

- Downloads / mo: 1.2M
- Stars: 639
- Last release: 1.13.0
- License: Apache-2.0
- Capabilities: [From the ADBC PostgreSQL docs](https://arrow.apache.org/adbc/current/driver/postgresql.html)

```sh
python3 -m pip install adbc-driver-postgresql adbc-driver-manager pyarrow
```

**pola-rs/polars** (40.4K stars)

[pola-rs/polars](https://github.com/pola-rs/polars) 

```python
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)

```

[py-polars/src/polars/io/database/_utils.py](https://github.com/pola-rs/polars/blob/6a40f554cd1583615374fb1fb128c130ecf9549e/py-polars/src/polars/io/database/_utils.py#L233-L257) · [More projects using ADBC PostgreSQL →](https://dashboard.exa.ai/playground/search?q=adbc-driver-postgresql%20GitHub%20projects)

**Quickstart**

```python
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())

```

From [dbapi.py](https://api.github.com/repos/apache/arrow-adbc/git/blobs/3a52b30780617d074483ac245097c0f276db8b44)

### aiopg

[GitHub](https://github.com/aio-libs/aiopg) · [PyPI](https://pypi.org/project/aiopg) · [Docs](https://aiopg.readthedocs.io/en/stable/)

Integrates PostgreSQL with asyncio.

- Downloads / mo: 685.1K
- Stars: 1.4K
- Last release: 1.4.0
- License: BSD
- Capabilities: [From the aiopg docs](https://aiopg.readthedocs.io/en/stable/)

```sh
python3 -m pip install aiopg
```

**aio-libs/aiohttp-demos** (749 stars)

[aio-libs/aiohttp-demos](https://github.com/aio-libs/aiohttp-demos) 

```python
async def pg_context(app):
    conf = app['config']['postgres']
    engine = await aiopg.sa.create_engine(
        database=conf['database'],
        user=conf['user'],
        password=conf['password'],
        host=conf['host'],
        port=conf['port'],
        minsize=conf['minsize'],
        maxsize=conf['maxsize'],
    )
    app['db'] = engine

    yield

    app['db'].close()
    await app['db'].wait_closed()

```

[demos/polls/aiohttpdemo_polls/db.py](https://github.com/aio-libs/aiohttp-demos/blob/22c4cb112d3ecf8df7113ba337570ba2081d4797/demos/polls/aiohttpdemo_polls/db.py#L36-L52) · [More projects using aiopg →](https://dashboard.exa.ai/playground/search?q=aiopg%20GitHub%20projects)

**Quickstart**

```python
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())

```

From [index.html](https://aiopg.readthedocs.io/en/stable/)

### PyGreSQL

[GitHub](https://github.com/PyGreSQL/PyGreSQL) · [PyPI](https://pypi.org/project/pygresql) · [Docs](https://pypi.org/pypi/pygresql/6.2.3/json)

Provides Python interfaces to PostgreSQL.

- Downloads / mo: 339.5K
- Stars: 48
- Last release: 6.2.3
- License: PostgreSQL
- Capabilities: [From the PyGreSQL docs](https://pypi.org/pypi/pygresql/6.2.3/json)

```sh
python3 -m pip install pygresql
```

**sqlobject/sqlobject** (157 stars)

[sqlobject/sqlobject](https://github.com/sqlobject/sqlobject) 

```python
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

```

[sqlobject/postgres/pgconnection.py](https://github.com/sqlobject/sqlobject/blob/1dfb07bca80c35f2575e00e05fc9bdf6a40d6421/sqlobject/postgres/pgconnection.py#L219-L254) · [More projects using PyGreSQL →](https://dashboard.exa.ai/playground/search?q=pygresql%20GitHub%20projects)

**Quickstart**

```python
import pgdb
conn = pgdb.connect(database="test", user="postgres")
cur = conn.cursor()
cur.execute("SELECT 1")
print(cur.fetchone())
cur.close()
conn.close()

```

From [module.html](https://pygresql.github.io/contents/pgdb/module.html)

## FAQ

### Which Python PostgreSQL library should I use?

[Psycopg](#psycopg) suits new projects and offers synchronous and native async interfaces. [asyncpg](#asyncpg) suits asyncio services that want a dedicated protocol client and pool. [pg8000](#pg) suits environments that cannot install libpq.

### psycopg2 vs Psycopg: which should I use?

[Psycopg](#psycopg) is the current generation of the adapter. Its publisher recommends it for new projects and keeps [psycopg2](#psycopg-binary) for existing integrations.

### What is asyncpg?

[asyncpg](#asyncpg) is an asyncio PostgreSQL driver with its own protocol client and connection pool. It does not offer a synchronous DB-API interface.

### What is pg8000?

[pg8000](#pg) is a pure Python PostgreSQL driver with both DB-API and native query interfaces. It does not depend on libpq.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python PostgreSQL libraries Psycopg psycopg2 asyncpg pg8000 drivers async connection pooling COPY code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
