I'm playing around with SQLAlchemy core in Python, and I've read over the documentation numerous times and still need clarification about engine.execute()
vs connection.execute()
.
As I understand it, engine.execute()
is the same as doing connection.execute()
, followed by connection.close()
.
The tutorials I've followed let me to use this in my code:
Initial setup in script
try:
engine = db.create_engine("postgres://user:pass@ip/dbname", connect_args={'connect_timeout': 5})
connection = engine.connect()
metadata = db.MetaData()
except exc.OperationalError:
print_error(f":: Could not connect to {db_ip}!")
sys.exit()
Then, I have functions that handle my database access, for example:
def add_user(a_username):
query = db.insert(table_users).values(username=a_username)
connection.execute(query)
Am I supposed to be calling connection.close()
before my script ends? Or is that handled efficiently enough by itself? Would I be better off closing the connection at the end of add_user()
, or is that inefficient?
If I do need to be calling connection.close()
before the script ends, does that mean interrupting the script will cause hanging connections on my Postgres DB?