2 回答

TA貢獻1877條經驗 獲得超1個贊
嘗試池連接
來自官方文檔:
在向請求者提供連接時,池會打開多個連接并處理線程安全
實現連接池,可以復用已有的連接
dbconfig = {
"database": "test",
"user": "joe"
}
cnxpool = mysql.connector.connect(pool_name = "mypool",
pool_size = 3, # or any number to suit your need
**dbconfig)
# then to get a connection from pool use
cnx = cnxpool.get_connection()
有關更多信息,請參閱:https ://dev.mysql.com/doc/connector-python/en/connector-python-connection-pooling.html

TA貢獻1863條經驗 獲得超2個贊
如果有人對在沒有 ORM 的情況下處理 sql 連接的方法感興趣,我做了以下步驟來結合 MySQL Connections Pool、上下文管理器和 Flask:
SQL_CONN_POOL = pooling.MySQLConnectionPool(
pool_name="mysqlpool",
pool_size=10,
user=DB_USER,
password=DB_PASS,
host=DB_HOST,
database=DATABASE,
auth_plugin=DB_PLUGIN
)
@contextmanager
def mysql_connection_from_pool() -> "conn":
conn_pool = SQL_CONN_POOL # get connection from the pool, all the rest is the same
# you can add print(conn_pool) here to be sure that pool
# is the same for each http request
_conn = conn_pool.get_connection()
try:
yield _conn
except (Exception, Error) as ex:
# if error happened all made changes during the connection will be rolled back:
_conn.rollback()
# this statement re-raise error to let it be handled in outer scope:
raise
else:
# if everything is fine commit all changes to save them in db:
_conn.commit()
finally:
# actually it returns cursor to the pool, rather than close it
_conn.close()
@contextmanager
def mysql_curs_from_pool() -> "curs":
with mysql_connection_from_pool() as _conn:
_curs = _conn.cursor()
try:
yield _curs
finally:
_curs.close()
添加回答
舉報