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...