Python Sqlite3 SQL执行闭合对象

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执行闭合对象)