简体   繁体   English

是否应将同一对象用于独立的不同数据库操作?

[英]Should I use the same object for independent, different database operations?

class DB:
  def insert(self, data):
      #connect to database and insert the data into Table.

  def update(self, data):
      #connect to database and update the Table.

class EditInfo:
  def Insert_into_Table(self, data):
      self.object1 = DB() #created the object here
      self.object1.insert()

  def update_the_Table(self, data):
      self.object1.update() #Reusing the same object created before  

Referring to object1 , is it a good idea to create just one object( like self.object1) for a class that does the Database operations frequently, and reusing it in several methods (like in Insert_into_Table(), update_the_Table() ) without bothering to delete it ? 提到object1 ,最好是为一个经常执行数据库操作的类创建一个对象(例如self.object1),并以多种方法重用它(例如在Insert_into_Table(),update_the_Table()中),而不用担心删除它 ?
Or, should I delete, calling __del__ , the object created before and creating a new object every-time the need arises ? 或者,是否应该删除调用__del__的对象,并在每次需要时创建一个新对象?

It's reasonable to have a very low level object that is used to access the db and is reused over and over again. 有一个非常低级的对象用于访问数据库,并一遍又一遍地重用是合理的。 In fact I think you're better off having a singleton that does the db access and is only created once per session. 实际上,我认为您最好有一个单例来执行数据库访问,并且每个会话仅创建一次。 The only question from there is if you should have layers between the DB object and your business logic (likely answer is yes). 唯一的问题是,是否应在数据库对象和业务逻辑之间设置层(可能的答案是肯定的)。

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

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