import sqlite3
import warnings
class SQLCommand(object):
"""
sqlite3 SQL执行闭合对象
"""
# 游标
cursor = None
def __init__(self, path):
"""
sqlite3文件路径
:param path:
"""
self.path = path
def __enter__(self):
self.conn = sqlite3.connect(self.path)
self.cursor = self.conn.cursor()
return self.cursor
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type:
warnings.warn('SQLCommand Error: {}\n{}\n{}'.format(
exc_type, exc_val, exc_tb
))
else:
self.conn.commit()
self.conn.close()
def execute(self, *args, **kwargs):
return self.cursor.execute(*args, **kwargs)
if __name__ == '__main__':
import uuid
import random
with SQLCommand('test.sqlite') as cursor:
cursor.execute('CREATE TABLE IF NOT EXISTS `TEST1` (T_ID CHAR(36) PRIMARY KEY, T_VALUE INTEGER DEFAULT 0)')
for i in range(10):
cursor.execute(
'INSERT INTO `TEST1` (T_ID, T_VALUE) VALUES (?, ?)',
(str(uuid.uuid1()), str(random.randint(0, 100)))
)
with SQLCommand('test.sqlite') as cursor:
cursor.execute('SELECT * FROM `TEST1`')
for r in cursor:
print(r)
# ('926def34-64e5-11e9-afba-1002b543289d', 44)
# ('926f75e2-64e5-11e9-b980-1002b543289d', 80)
# ('926f75e3-64e5-11e9-8305-1002b543289d', 38)
# ('926f75e4-64e5-11e9-9432-1002b543289d', 5)
# ('926f75e5-64e5-11e9-8338-1002b543289d', 76)
# ('926f75e6-64e5-11e9-844d-1002b543289d', 41)
# ('926f75e7-64e5-11e9-92e1-1002b543289d', 50)
# ('926f75e8-64e5-11e9-a6e8-1002b543289d', 43)
# ('926f75e9-64e5-11e9-9e7d-1002b543289d', 57)
# ('926f9cf8-64e5-11e9-b711-1002b543289d', 66)
Python Sqlite3 SQL执行闭合对象
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 使用 execute 方法执行一条SQL语句,如果带有参数可以使用占位符来传递参数。使用占位符已经考虑到转码的问...
- 由于许多潜在的pandas用户对SQL有一定的了 解 ,因此本页旨在提供一些使用pandas来执行各种SQL操作的...
- 第六部分:SQL 和对象关系映射 原文:Part VI: SQL and Object Relational Ma...