Skip to content

Commit bb693e6

Browse files
chore: update context manager sample usage (#262)
1 parent 2ff8708 commit bb693e6

File tree

1 file changed

+34
-28
lines changed

1 file changed

+34
-28
lines changed

README.md

+34-28
Original file line numberDiff line numberDiff line change
@@ -183,43 +183,49 @@ Connector as a context manager:
183183
from google.cloud.alloydb.connector import Connector
184184
import sqlalchemy
185185

186-
# build connection
187-
def getconn():
188-
with Connector() as connector:
186+
# helper function to return SQLAlchemy connection pool
187+
def init_connection_pool(connector: Connector) -> sqlalchemy.engine.Engine:
188+
# function used to generate database connection
189+
def getconn():
189190
conn = connector.connect(
190191
"projects/<YOUR_PROJECT>/locations/<YOUR_REGION>/clusters/<YOUR_CLUSTER>/instances/<YOUR_INSTANCE>",
191192
"pg8000",
192193
user="my-user",
193194
password="my-password",
194195
db="my-db-name"
195196
)
196-
return conn
197-
198-
# create connection pool
199-
pool = sqlalchemy.create_engine(
200-
"postgresql+pg8000://",
201-
creator=getconn,
202-
)
203-
204-
# insert statement
205-
insert_stmt = sqlalchemy.text(
206-
"INSERT INTO my_table (id, title) VALUES (:id, :title)",
207-
)
208-
209-
# interact with AlloyDB database using connection pool
210-
with pool.connect() as db_conn:
211-
# insert into database
212-
db_conn.execute(insert_stmt, parameters={"id": "book1", "title": "Book One"})
213-
214-
# commit transaction (SQLAlchemy v2.X.X is commit as you go)
215-
db_conn.commit()
197+
return conn
216198

217-
# query database
218-
result = db_conn.execute(sqlalchemy.text("SELECT * from my_table")).fetchall()
199+
# create connection pool
200+
pool = sqlalchemy.create_engine(
201+
"postgresql+pg8000://",
202+
creator=getconn,
203+
)
204+
return pool
219205

220-
# Do something with the results
221-
for row in result:
222-
print(row)
206+
# initialize Connector as context manager
207+
with Connector() as connector:
208+
# initialize connection pool
209+
pool = init_connection_pool(connector)
210+
# insert statement
211+
insert_stmt = sqlalchemy.text(
212+
"INSERT INTO my_table (id, title) VALUES (:id, :title)",
213+
)
214+
215+
# interact with AlloyDB database using connection pool
216+
with pool.connect() as db_conn:
217+
# insert into database
218+
db_conn.execute(insert_stmt, parameters={"id": "book1", "title": "Book One"})
219+
220+
# commit transaction (SQLAlchemy v2.X.X is commit as you go)
221+
db_conn.commit()
222+
223+
# query database
224+
result = db_conn.execute(sqlalchemy.text("SELECT * from my_table")).fetchall()
225+
226+
# Do something with the results
227+
for row in result:
228+
print(row)
223229
```
224230

225231
### Async Driver Usage

0 commit comments

Comments
 (0)