Best way to access and close a postgres database using python dataset

import dataset    
from sqlalchemy.pool import NullPool

db = dataset.connect(path_database, engine_kwargs={'poolclass': NullPool})

table_f1 = db['name_table']
# Do operations on table_f1

db.commit()
db.executable.close()

I use this code to access the postgres database and sometimes write to you. Finally, I close it. Is the above code the best way to access and close? Alternatively better code below?

import dataset    
from sqlalchemy.pool import NullPool

with dataset.connect(path_database, engine_kwargs={'poolclass': NullPool}) as db:
    table_f1 = db['name_table']
    # Do operations on table_f1

    db.commit()

In particular, I want to make 100% sure that after this part of the code there is no connection with the postgres database. What is the best way to achieve this? option 1 or option 2?

+6
source share
1 answer

, , 2 ( ), , (/ ).

( Github repo, , ?)

, db.commit() db.executable.close() 2:

import dataset    
from sqlalchemy.pool import NullPool

with dataset.connect(path_database, engine_kwargs={'poolclass': NullPool}) as db:
    table_f1 = db['name_table']
    print(db.local.conn.closed) # >>>False

    # Do operations on table_f1
    # end of the context manager, trying to commit 

db.executable.close()
print(db.local.conn.closed) # >>>True

:

# db['name_table'].all() ==> throws an error due to closed connection

... (- ?):

# db['new_table'] ==> enough to add a new table 

, , (db = None db.metadata = None)


SQLAlchemy:

from sqlalchemy import *
from sqlalchemy.pool import NullPool

engine = create_engine('postgresql:///datatest', poolclass=NullPool) 

connection = engine.connect()
meta = MetaData(engine)
t1 = Table('Table_1', meta,
           Column('id', Integer, primary_key=True),
           Column('name',String))
t1.create()
connection.close()

t2 = Table('Table_2', meta,
           Column('id', Integer, primary_key=True),
           Column('name',String))
t2.create()
# table_2 is created in database

EDIT:

( Ilja EverilΓ€ )

meta = MetaData(connection), , , .

+4

All Articles