Interactive SQL shell
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|