Logo F2FInterview

Python Advanced Interview Questions

Q   |   QA

To access a database, it is best to define a class. Here I define a class called Table which allows me to retrieve data (__getitem__) and to know the number of records (__len__).

class Table:
     def __init__(self, db, name):
          self.db = db
          self.name = name
          self.dbc = self.db.cursor()

     def __getitem__(self, item):
          self.dbc.execute("select * from %s limit %s, 1" %(self.name, item))
          return self.dbc.fetchone()

     def __len__(self):
          self.dbc.execute("select count(*) from %s" % (self.name))
          l = int(self.dbc.fetchone()[0])
          return l  

In order to link this F2FInterview's page as Reference on your website or Blog, click on below text area and pres (CTRL-C) to copy the code in clipboard or right click then copy the following lines after that paste into your website or Blog.

Get Reference Link To This Page: (copy below code by (CTRL-C) and paste into your website or Blog)
HTML Rendering of above code: