Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Korakot Chaovavanich http://korakot.stumbleupon.com

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Interactive SQL shell

To help myself learning about SQL in Symbain DBMS, I write
a small script to act as an interactive SQL shell.
First you need to connect to the database.
   1  
   2  >>> import e32db
   3  >>> db = e32db.Dbms()
   4  >>> dbv = e32db.Db_view()
   5  >>> db.open(u'C:\\test.db')  # might need db.create(...)

Here's the query simplification code.
   1  
   2  def Q(sql):
   3      if sql.upper().startswith('SELECT'):
   4          dbv.prepare(db, unicode(sql))
   5          dbv.first_line()
   6          rows = []
   7          maxlen = [0] * dbv.col_count()
   8          for i in range(dbv.count_line()):
   9              dbv.get_line()
  10              result = []
  11              for i in range(dbv.col_count()):
  12                  try:
  13                      val = dbv.col(i+1)
  14                  except:    # in case coltype 16
  15                      val = None
  16                  result.append(val)
  17                  maxlen[i] = max(maxlen[i], len(str(val)))
  18              rows.append(result)
  19              dbv.next_line()
  20          fmt = '|'+ '|'.join(['%%%ds' % n for n in maxlen]) + '|'
  21          for row in rows:
  22              print fmt % tuple(row) 
  23      else:
  24          n = db.execute(unicode(sql))
  25          print '%d rows affected' % n

After that, playing with SQL is quite simple.
   1  
   2  >>> Q("CREATE TABLE person (id COUNTER, name VARCHAR)")
   3  0 rows affected
   4  >>> Q("INSERT INTO person(name) VALUES ('Korakot')")
   5  1 rows affected
   6  >>> Q("INSERT INTO person(name) VALUES ('morning_glory')")
   7  1 rows affected
   8  >>> Q("SELECT * from person")
   9  |0|      Korakot|
  10  |1|morning_glory|
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS