2017-08-10 65 views
0

我正在使用karellen-sqlite Python模块中的set_update_hook()函数来自动将数据库更改发送到函数。基本上,它的工作原理是这样的:将数据包含在钩子中?

from pysqlite2 import connect 

def hook(conn, op, db_name, table_name, rowid): 
    """Handle notification here. Do not modify the connection!""" 

with connect(":memory:") as conn: 
    conn.set_update_hook(hook) 
    conn.execute("CREATE TABLE a (int id);") 
    conn.execute("INSERT INTO a VALUES (1);") 

我想,以确定是否发送到hook的信息包含已插入,更新或删除数据库中的数据。

所以,执行一个insert后,我印刷的hook的参数的值:

conn = ['DataError', 'DatabaseError', 'Error', 'IntegrityError', 'InterfaceError', 'InternalError', 'NotSupportedError', 'OperationalError', 'ProgrammingError', 'Warning', '__call__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_update_hook', '_update_hook_cb', '_update_hook_last_error', 'close', 'commit', 'create_aggregate', 'create_collation', 'create_function', 'cursor', 'enable_load_extension', 'execute', 'executemany', 'executescript', 'in_transaction', 'interrupt', 'isolation_level', 'iterdump', 'last_update_hook_error', 'load_extension', 'rollback', 'row_factory', 'set_authorizer', 'set_progress_handler', 'set_trace_callback', 'set_update_hook', 'text_factory', 'total_changes'] 

op = UpdateHookOps.SQLITE_INSERT 

db_name = main 

table_name = test 

rowid = 3 

但哪一个数据?我是否必须执行单独的查询来检索它(在插入或更新的情况下)?

谢谢:)

回答

1

这种机制是sqlite3_update_hook() C API function周围的包装:

的第一个参数回调的第三个参数sqlite3_update_hook()的副本。第二个回调参数是SQLITE_INSERT,SQLITE_DELETESQLITE_UPDATE之一,具体取决于导致回调被调用的操作。回调的第三个和第四个参数包含指向包含受影响行的数据库和表名称的指针。最后的回调参数是行的rowid。在更新的情况下,这是更新发生后的rowid。

所以你只是得到足够的信息来识别行。