@@ -183,43 +183,49 @@ Connector as a context manager:
183
183
from google.cloud.alloydb.connector import Connector
184
184
import sqlalchemy
185
185
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 ():
189
190
conn = connector.connect(
190
191
" projects/<YOUR_PROJECT>/locations/<YOUR_REGION>/clusters/<YOUR_CLUSTER>/instances/<YOUR_INSTANCE>" ,
191
192
" pg8000" ,
192
193
user = " my-user" ,
193
194
password = " my-password" ,
194
195
db = " my-db-name"
195
196
)
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
216
198
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
219
205
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)
223
229
```
224
230
225
231
### Async Driver Usage
0 commit comments