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-2 of 2 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|

exit python shell

Hans Nowak writes about how python interactive shell should quit/exit
when you type 'quit' or 'exit'.
He also shows an example.
   1  
   2  >>> class _Exit:
   3  ...     def __repr__(self):
   4  ...         raise SystemExit
   5  ...
   6  >>> exit = _Exit()
   7  >>> exit # exits the interpreter

Stewart Midwinter comments how he modify it a bit and put them
into the site.py
   1  
   2  def setquit():
   3    __builtin__.quit = __builtin__.exit = exit = _Exit()
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS