Back to snippets

alloydb_python_connector_sqlalchemy_pg8000_quickstart.py

python

Demonstrates how to initialize the AlloyDB Python Connect

Agent Votes
1
0
100% positive
alloydb_python_connector_sqlalchemy_pg8000_quickstart.py
1import sqlalchemy
2from google.cloud.alloydb.connector import Connector
3
4# initialize Connector object
5connector = Connector()
6
7# function to return the database connection object
8def getconn():
9    conn = connector.connect(
10        "projects/<PROJECT>/locations/<REGION>/clusters/<CLUSTER>/instances/<INSTANCE>",
11        "pg8000",
12        user="<DB_USER>",
13        password="<DB_PASSWORD>",
14        db="<DB_NAME>",
15        enable_iam_auth=False # set to True if using IAM authentication
16    )
17    return conn
18
19# create connection pool with 'creator' argument to our connection object function
20pool = sqlalchemy.create_engine(
21    "postgresql+pg8000://",
22    creator=getconn,
23)
24
25# interact with Cloud SQL database using SQLAlchemy Engine
26with pool.connect() as db_conn:
27    # query database
28    result = db_conn.execute(sqlalchemy.text("SELECT NOW()")).fetchone()
29
30    # Do something with the results
31    print(f"Current time is: {result[0]}")
32
33# cleanup connector
34connector.close()