使用Sqlite& amp;打印每个查询蟒蛇

时间:2016-05-13 11:55:35

标签: python sqlite

我有一个带有Tkinter的python脚本,我想在后台打印每个查询在Sqlite数据库中做的(只是为了好玩):

我有一个数据库对象:

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()

还有一个Task对象

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()

当我这样做new_task = Task('Hello')时,我想在CLI中自动注销,如下所示:

* executed in 4ms :
    INSERT INTO tasks (name) VALUES('Hello');

有什么想法吗?提前谢谢!

1 个答案:

答案 0 :(得分:1)

这是你在找什么?我考虑过使用装饰器,某种stopwatch

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

但后来我想到了背景管理者,也许(我不是合适的判断者)更适合这种工作。借用here的代码我最终得到了(哈哈):

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))

我已经测试了一下,但是将它应用到你的情况我可能会犯一些错误,因为我必须稍微更改Task __init__以便能够重用SQL命令。