[Python数据库] python操作sqlite函数化

class部分:

class Database(object):
    
    filepath = 'db路径'

    def __init__(self, database=None):
        self.database = self.filepath if database is None else database
        self.connection = None
        self.cursor = None

    def __del__(self):
        self.disconnect()

    def connect(self, who="server"):
        self.connection = sqlite3.connect(self.database, timeout=3, isolation_level=None, check_same_thread=False)
        self.cursor = self.connection.cursor()
        
    def disconnect(self):
        if self.cursor:
            self.cursor.close()

        if self.connection:
            self.connection.close()

    def commit(self):
        self.connection.commit()

    def execute(self, statement, arguments=None):
        while True:
            try:
                if arguments:
                    self.cursor.execute(statement, arguments)
                else:
                    self.cursor.execute(statement)
                self.commit()
            except sqlite3.OperationalError, ex:
                    raise
            else:
                break

        if statement.lstrip().upper().startswith("SELECT"):
            return self.cursor.fetchall()
            
    def init(self):
        self.execute("CREATE TABLE data("
                  "id integer primary key autoincrement, "
                  "status CHAR(16), "
                  "result CHAR(8192), "
                  "object CHAR(1024)"
                  ")")

实例化使用:

db = Database()
db.connect()
db.execute("update data set result=? where id=?",(result, id))
db.execute("update data set status='done' where id='{}'".format(id))
select_result = db.execute("select status from data where id='{}'".format(id))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值