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