让 Python 更加充分的使用 Sqlite3

即使在处理SQL事务的中间,也会发生讨厌的事情。为了避免手动处理回滚或提交,你可以简单地使用连接对象作为上下文管理器。 在以下示例中,我们创建了一个表,并错误地插入了重复的值:

import sqlite3 connection = sqlite3.connect(':memory:') with connection:     connection.execute(         'CREATE TABLE events(ts, msg, PRIMARY KEY(ts, msg))') try:     with connection:         connection.executemany('INSERT INTO events VALUES (?, ?)', [             (1, 'foo'),             (2, 'bar'),             (3, 'baz'),             (1, 'foo'),         ]) except (sqlite3.OperationalError, sqlite3.IntegrityError) as e:     print('Could not complete operation:', e)      for row in connection.execute('SELECT * FROM events'):     print(row)      connection.close()

首页 - Wiki
Copyright © 2011-2026 iteam. Current version is 2.154.0. UTC+08:00, 2026-02-26 06:40
浙ICP备14020137号-1 $访客地图$