简体   繁体   English

SQLAlchemy 2.0 迁移 - 连接到数据库

[英]SQLAlchemy 2.0 migration - Connection to Database

I am just testing out the SQLAlchemy 1.4 library out and I noticed in the foreseeable future they changing certain core functionalities.我只是在测试 SQLAlchemy 1.4 库,我注意到在可预见的将来它们会改变某些核心功能。 I generally connect to a database shown below, moving forward they mentioned they are going to remove this bind method on the MetaBase class, what is going to be the set standard of writing this?我通常连接到如下所示的数据库,然后他们提到他们将在MetaBase class 上删除这个bind方法,编写这个的设定标准是什么?

def output_log(msg):
    connector = create_engine("mylogin")
    metadata = MetaData(bind=connector)
    log = Table("mytable", metadata, autoload=True)
    sess = connector.connect()
    i = insert(log).values({"Message": msg})
    sess.execute(i)
    sess.close()

The changes and background for this are described in “Implicit” and “Connectionless” execution, “bound metadata” removed .对此的更改和背景在“隐式”和“无连接”执行中描述,“绑定元数据”已删除

You can rewrite your code as follows:您可以按如下方式重写代码:

def output_log(msg):
    engine = create_engine("mylogin")
    metadata = MetaData()
    log = Table("mytable", metadata, autoload_with=engine)
    sess = engine.connect()
    i = log.insert().values({"Message": msg})
    sess.execute(i)
    sess.commit()
    sess.close()

Or for completeness using with :或者为了完整性使用with

    with engine.begin() as sess:
        i = log.insert().values({"Message": msg})
        sess.execute(i)

And the other half option with the future commit :未来commit的另一half选项:

    with engine.connect() as sess:
        i = log.insert().values({"Message": msg})
        sess.execute(i)
        sess.commit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM