SQLAlchemy:如何在使用它们之前建立连接?
SQLAlchemy: how to establish connection before using them?
由于连接建立,第一次查询执行比连续调用花费的时间长得多。
例如:
connection_string = '...'
engine = create_engine(connection_string)
first_query = engine.execute('SELECT * FROM Table1').first() # Takes about 2.2 seconds
same_table_second_query = engine.execute('SELECT * FROM Table1').first() # Takes about 0.8 seconds
other_table_query = engine.execute('SELECT * FROM Table2').first() # Takes about 0.8 seconds
在我的例子中,池旨在为多个线程提供服务(我会相应地调整它的大小)并且性能非常关键。
有没有办法在使用之前初始化/建立整个池?如果有不同的解决方案,我很乐意学习。
编辑:
如果我使用返回的连接而不是引擎:
connection = engine.connect()
first_query = connection.execute('SELECT * FROM Table1').first()
same_table_second_query = connection.execute('SELECT * FROM Table1').first()
两者都需要大约0.07s。
但这并不能解决我的问题,因为我仍然需要一个已建立的池来在线程之间共享。
Is there a way to initialize / establish the entire pool before using it?
你可以这样做:
engine = sa.create_engine(connection_url)
conn_list = []
for i in range(engine.pool.size()):
conn_list.append(engine.connect())
print(engine.pool.status())
# Pool size: 5 Connections in pool: 0 Current Overflow: 0 Current Checked out connections: 5
for conn in conn_list:
conn.close()
print(engine.pool.status())
# Pool size: 5 Connections in pool: 5 Current Overflow: 0 Current Checked out connections: 0
但它所做的只是产生建立连接的成本up-front。这也意味着您可能正在创建实际上并不需要的连接。
由于连接建立,第一次查询执行比连续调用花费的时间长得多。
例如:
connection_string = '...'
engine = create_engine(connection_string)
first_query = engine.execute('SELECT * FROM Table1').first() # Takes about 2.2 seconds
same_table_second_query = engine.execute('SELECT * FROM Table1').first() # Takes about 0.8 seconds
other_table_query = engine.execute('SELECT * FROM Table2').first() # Takes about 0.8 seconds
在我的例子中,池旨在为多个线程提供服务(我会相应地调整它的大小)并且性能非常关键。
有没有办法在使用之前初始化/建立整个池?如果有不同的解决方案,我很乐意学习。
编辑:
如果我使用返回的连接而不是引擎:
connection = engine.connect()
first_query = connection.execute('SELECT * FROM Table1').first()
same_table_second_query = connection.execute('SELECT * FROM Table1').first()
两者都需要大约0.07s。 但这并不能解决我的问题,因为我仍然需要一个已建立的池来在线程之间共享。
Is there a way to initialize / establish the entire pool before using it?
你可以这样做:
engine = sa.create_engine(connection_url)
conn_list = []
for i in range(engine.pool.size()):
conn_list.append(engine.connect())
print(engine.pool.status())
# Pool size: 5 Connections in pool: 0 Current Overflow: 0 Current Checked out connections: 5
for conn in conn_list:
conn.close()
print(engine.pool.status())
# Pool size: 5 Connections in pool: 5 Current Overflow: 0 Current Checked out connections: 0
但它所做的只是产生建立连接的成本up-front。这也意味着您可能正在创建实际上并不需要的连接。