简体   繁体   中英

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 ?
Or, should I delete, calling __del__ , the object created before and creating a new object every-time the need arises ?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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