kiran
03/08/2023, 6:43 PMpsycopg2
, I use a try/finally
because leaving the context manager doesn’t close the connection. So, I would do things like this:
sql = ...
conn = ...
try:
with conn:
with conn.cursor() as curs:
curs.execute(sql)
...
finally:
conn.close()
Since psycopg2
specifically notes that the connection doesn’t get closed, I would like to confirm that the prefect-sqlalchemy SQLAlchemyConnector
does close the connection automatically (as your docs say) when using the context manager like below and therefore, I don’t need to use the try/finally
. I’m using the postgresql+psycopg2
driver. Thanks!
with SqlAlchemyConnector.load("MY_BLOCK") as database:
database.execute("CREATE TABLE IF NOT EXISTS customers (name varchar, address varchar);")
database.execute_many(
"INSERT INTO customers (name, address) VALUES (:name, :address);",
seq_of_parameters=[
{"name": "Ford", "address": "Highway 42"},
{"name": "Unknown", "address": "Space"},
{"name": "Me", "address": "Myway 88"},
],
)
results = database.fetch_many("SELECT * FROM customers", size=2)
print(results)
results = database.fetch_many("SELECT * FROM customers", size=2)
print(results)
Nate
03/08/2023, 7:37 PMSQLAlchemyConnector
should manage your db engine (and any connections it has) when used as a context manager
you could check out how that works herekiran
03/08/2023, 9:43 PMfield_names = [i[0] for i in cursor.description]
?from sqlalchemy.engine.cursor import CursorResult
but I’m not sure how to properly get itNate
03/10/2023, 8:43 PMSQLAlchemyConnector
to get a connection and get a cursor from that
is that what you're looking for?kiran
03/10/2023, 9:16 PM*AttributeError:* '_trans_ctx' object has no attribute 'cursor'
redshift_db = SqlAlchemyConnector.load("redshift-db")
conn = redshift_db.get_connection()
print(dir(conn))
cursor = conn.cursor()
Nate
03/10/2023, 9:17 PMwith SqlAlchemyConnector.load("redshift-db") as redshift_db:
conn = redshift_db.get_connection()
print(dir(conn))
cursor = conn.cursor()
kiran
03/10/2023, 9:23 PM[
'__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__enter__',
'__eq__',
'__exit__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'close_with_result',
'conn',
'transaction'
]
Nate
03/10/2023, 9:27 PMkiran
03/10/2023, 9:30 PMcursor
, right? Or did I misunderstandNate
03/10/2023, 9:31 PMprefect-sqlalchemy
so I'm looking into it nowkiran
03/10/2023, 9:32 PMcx_Oracle
on its own just fine