Connect with Python Early availability
Connect to an Aiven for AlloyDB Omni database using Python 3 and the psycopg2 library.
Prerequisites
-
Aiven for AlloyDB Omni service running
-
Python 3.6 or later
-
Python
psycopg2
library, which you can install with the following commands:pip install psycopg2
or
python3 -m pip install psycopg2
Connect to a service
-
Create a file named
main.py
with the following content:import psycopg2
def main():
conn = psycopg2.connect('POSTGRESQL_URI')
query_sql = 'SELECT VERSION()'
cur = conn.cursor()
cur.execute(query_sql)
version = cur.fetchone()[0]
print(version)
if __name__ == "__main__":
main()Replace
SERVICE_URI
with the service URI available on the Overview page in the Aiven Console.This code opens a connection to the database, runs a query checking the database version, and prints the response.
noteBy default, the connection string (
SERVICE_URI
) specifiessslmode=require
, which doesn't verify the CA certificate. For production environments, it's recommended to change it tosslmode=verify-ca
and include the certificate. -
Run the code:
python3 main.py
Expect output like:
PostgreSQL 15.5 on x86_64-pc-linux-gnu, compiled by [...]