Print each queries with Sqlite & Python
我有一个带有tkinter的python脚本,我想在后台打印sqlite数据库中的每个查询(只是为了好玩):
我有一个数据库对象:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import sqlite3 class Database(): def __init__(self): try: sqlite3.enable_callback_tracebacks(True) self.connection = sqlite3.connect('databases.sqlite') self.cursor = self.connection.cursor() self.cursor.execute(""" CREATE TABLE .... """ ) except: print('error in database connection') def __del__(self): self.cursor.close() |
和任务对象
1 2 3 4 5 6 7 | class Task(): def __init__(self, name="no_name"): self.database = Database() data = {"name" : name } self.database.cursor.execute("INSERT INTO tasks(name) VALUES(:name)" , data ) self.database.connection.commit() |
当我这样做时,我希望在cli中有一个自动输出,如下所示:
1 2 | * executed in 4ms : INSERT INTO tasks (name) VALUES('Hello'); |
有什么想法吗?提前谢谢!
这就是你要找的吗?我考虑过使用decorator,一种
1 2 3 4 5 6 7 8 9 10 | import time def stopwatch(func): def wrapper(*args,**kwargs): start = time.time() func(*args,**kwargs) end = time.time() timed = int((end - start)*1000) print(timed) return wrapper |
但后来我想到了上下文管理器,也许(我不是判断的合适人选)更适合这种工作。从这里借用代码我最终得到了(哈哈)这个:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class Timer: def __enter__(self): self.start = time.clock() return self def __exit__(self, *args): self.end = time.clock() # format as milliseconds self.interval = int((self.end - self.start) * 1000) class Task(): def __init__(self, name="no_name"): sql_commnad ="INSERT INTO tasks(name) VALUES({});".format(name) # do the database thingy inside the Timer context with Timer() as t: self.database = Database() self.database.cursor.execute(sql) self.database.connection.commit() print("* executed in {}ms :".format(t.interval)) print(" {}".format(sql_command)) |
我对它进行了一点测试,但是将它应用到您的案例中,我可能犯了一些错误,因为我需要稍微更改