An Example Dbms

dbms database class

  1  

  2 # Filename: db.py save in your Python dir
  3 import e32db
  4  
  5 class db:
  6 def __init__(self, dbpath):
  7 self.db = e32db.Dbms()
  8 self.dbv = e32db.Db_view()
  9 self.reset_counters()
  10 try:
  11 self.db.open(unicode(dbpath))
  12 except:
  13 self.db.create(unicode(dbpath))
  14 self.db.open(unicode(dbpath))
  15  
  16 def reset_counters(self):
  17 self.affected_rows = 0
  18 self.num_rows = 0
  19 self.__internal_counter = 0
  20  
  21 def query(self, sql):
  22 self.reset_counters()
  23 if sql.lower().startswith('select'):
  24 self.dbv.prepare(self.db, unicode(sql))
  25 self.dbv.first_line()
  26 self.num_rows = self.dbv.count_line()
  27 else:
  28 self.affected_rows = self.db.execute(unicode(sql))
  29  
  30 def next(self):
  31 row = {'id': 0}
  32 if self.num_rows < 1:
  33 self.reset_counters()
  34 raise StopIteration
  35 elif self.__internal_counter < self.num_rows:
  36 self.dbv.get_line()
  37 for i in range(self.dbv.col_count()):
  38 row[i] = self.dbv.col(i+1)
  39 self.dbv.next_line()
  40 self.__internal_counter += 1
  41 return row
  42 else:
  43 self.reset_counters()
  44 raise StopIteration
  45  
  46 def __iter__(self):
  47 return self


Now to create and fill db, create a file in the same dir as the db.py with this content:
  1  
  2 # Change __exec_path to the path of your python script dir
  3 __exec_path = "E:\\Python\\"
  4 dbname = "test"
  5  
  6 import sys
  7 sys.path.append(__exec_path)
  8 from db import db
  9  
  10 # This will open E:\\Python\test.db - it will be created first, if not existing
  11 mydb = db(__exec_path+dbname+'.db')
  12 mydb.query("create table testing (id counter, name varchar)")
  13 mydb.query("insert into testing (name) values ('test 1')")
  14 mydb.query("insert into testing (name) values ('test 2')")



Now go ahead and have fun:
  1  
  2 # Again change __exec_path to the path of your python script dir
  3 __exec_path = "E:\\Python\\"
  4 dbname = "test"
  5  
  6 import sys
  7 sys.path.append(__exec_path)
  8 from db import db
  9  
  10 # Opens E:\\Python\test.db
  11 mydb = db(__exec_path+dbname+'.db')
  12 mydb.query("select * from testing")
  13 for row in mydb:
  14 print "-> ",row[0]," ",row[1]," <-"

0 comments: