比如说,服务器有数千个请求表单客户端来处理他们的数据包并在同一时刻保存到数据库。
脚本必须为每个数据包做一些(比方说6)sql查询。
现在,脚本打开一次sql连接,并在完成每个数据包处理后关闭它。并且所有查询都在打开和关闭数据库连接之间运行。
class Processor:
def __init__(self, data):
self.data = data
def open_sql_connection(self):
"connection commands, strings etc"
def insert_to_db(self, table, data):
"inserting data to table of the database"
def close_sql_connection(self):
"disconnecting from database"
def process()
self.open_sql_connection()
"begin data process"
.....
self.insert_to_db(table_1, some_of_data)
"continue to data process"
.....
self.insert_to_db(table_2, some_of_data)
"continue to data process"
.....
self.insert_to_db(table_3, some_of_data)
self.close_sql_connection()
如果我在查询出现之前使脚本打开sql连接,并在完成每个查询后立即关闭它,我将获得任何好处。就像加快速度一样,让表格不那么繁忙,避免锁定等等。
class Processor:
def __init__(self, data):
self.data = data
def open_sql_connection(self):
"connection commands, strings etc"
def insert_to_db(self, table, data):
"inserting data to table of the database"
def close_sql_connection(self):
"disconnecting from database"
def process()
"begin data process"
.....
self.open_sql_connection()
self.insert_to_db(table_1, some_of_data)
self.close_sql_connection()
"continue to data process"
.....
self.open_sql_connection()
self.insert_to_db(table_2, some_of_data)
self.close_sql_connection()
"continue to data process"
.....
self.open_sql_connection()
self.insert_to_db(table_3, some_of_data)
self.close_sql_connection()
答案 0 :(得分:2)