打印使用SQLite与Python的

打印使用SQLite与Python的

问题描述:

每个查询我有Tkinter的Python脚本,我想在后台打印每个查询在SQLite数据库(只是为了好玩)所做的:打印使用SQLite与Python的

我有一个数据库对象:

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

和任务对象

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像这样的自动outpout:

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

任何想法?先谢谢你!

+0

作为一个便笺,我不确定,关于使用'__del__'来关闭游标。也许更重要的是,你是否关闭了连接?也许更好的方法'close..'做'self.cur.close(); self.conn.close()'。你是否需要在Task的'__init__'方法中使用'self'(因为它看起来就像这个类没有其他什么东西一样,只要摆脱自己,甚至可能“Task”太多了,函数可能就足够了[参见](https://www.youtube.com/watch?v=o9pEzgHorH0) – quapka

这是你在找什么?我想过用装饰的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命令。

+0

是的,使用装饰器是个好主意,但是如何在任务方法(如UPDATE或DELETE)上执行自动执行的SQL命令? – RousseauAlexandre

+0

也许[this](http://*.com/a/3467879/2377489)? – quapka

+0

是的我认为你是正确的装饰器函数。是否有任何方法来拦截每个游标方法(如'__setattr __()'方法)并打印查询? – RousseauAlexandre