Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python SQLAlchemy核心引擎.execute()与connection.execute()的比较_Python_Database_Sqlalchemy - Fatal编程技术网

Python SQLAlchemy核心引擎.execute()与connection.execute()的比较

Python SQLAlchemy核心引擎.execute()与connection.execute()的比较,python,database,sqlalchemy,Python,Database,Sqlalchemy,我正在使用Python中的SQLAlchemy core,我已经阅读了很多文档,仍然需要澄清engine.execute()vsconnection.execute() 据我所知,engine.execute()与执行connection.execute(),然后是connection.close() 我遵循的教程允许我在代码中使用以下内容: 脚本中的初始设置 try: engine = db.create_engine("postgres://user:pass@ip/dbname",

我正在使用Python中的SQLAlchemy core,我已经阅读了很多文档,仍然需要澄清
engine.execute()
vs
connection.execute()

据我所知,
engine.execute()
与执行
connection.execute()
,然后是
connection.close()

我遵循的教程允许我在代码中使用以下内容:

脚本中的初始设置

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()
然后,我有处理数据库访问的函数,例如:

def add_user(a_username):
    query = db.insert(table_users).values(username=a_username)
    connection.execute(query)
我是否应该在脚本结束前调用
connection.close()
?或者说,它本身是否足够有效地处理?在
add_user()
的末尾关闭连接会更好,还是效率低下

如果我确实需要在脚本结束之前调用
connection.close()
,这是否意味着中断脚本会导致Postgres DB上的连接挂起?

我发现更好地理解sqlalchemy中的不同交互范例很有帮助,以防您还没有阅读它

关于何时关闭db连接的问题:为每个语句执行创建和关闭连接确实是非常低效的。但是,您应该确保应用程序的全局流中没有连接泄漏