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()
我使用此代码访问postgres数据库,有时会写入它。最后,我关闭它。以上代码是访问和关闭它的最佳方式吗?或者,下面的代码更好吗?
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()
特别是,我想100%确定一旦完成这段代码就没有与postgres数据库的连接。哪个是实现它的更好方法?选项1或选项2?
答案 0 :(得分:6)
目前,主要问题是选项2( with statement )中使用的上下文管理器不处理连接,只处理transaction(最后提交/回滚)块)。
(这个问题已经报告给Github repo,也许行为会改变?)
因此,您应该在选项2中将db.commit()
替换为db.executable.close()
:
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
编辑:
(感谢IljaEverilä的评论,并关注the doc)
更好地调用meta = MetaData(connection)
以便在引擎处理时关闭连接,这将在上面的示例中引发错误,连接IS已关闭。