基于Python3的接口自动化总结(八)——Sqlite数据库

通过python连接Sqlite数据库
#! /usr/bin/env python3
# -*-coding:utf-8-*-
from sqlite3 import connect


class Sqlite:
    def __init__(self, db):
        self.db = db
        self.connection = None
        self.row_factory = None

    def _connect(self):
        self.connection = connect(self.db)
        self.row_factory = self.connection.row_factory
        # print(f"连接Sqlite数据库:{self.db}成功!")

    def connect(self):
        try:
            if self.connection:
                pass
                # print(f"已存在数据库连接:{self.db}")
            else:
                self._connect()
        except Exception as e:
            print(f"连接Sqlite数据库:{self.db}失败!异常信息:{e.args[0]}")
            raise

    def execute(self, sql, values=()):
        self.connect()
        row = []
        try:
            cur = self.connection.cursor()
            cur.execute(sql, values)
            row = cur.fetchall()
            self.connection.commit()
            # print(f"执行sql语句成功:{sql}")
            cur.close()
        except Exception as e:
            print(f"执行sql语句失败:{sql}!异常信息:{e.args[0]}")
            self.connection.rollback()
            raise
        # return row
        finally:
            self.close()
            return row

    def executemany(self, sql, values=()):
        """根据序列重复执行 SQL 语句"""
        self.connect()
        try:
            cur = self.connection.cursor()
            cur.executemany(sql, values)
            self.connection.commit()
            # print(f"执行sql语句成功:{sql}")
            cur.close()
        except Exception as e:
            print(f"执行sql语句失败:{sql}!异常信息:{e.args[0]}")
            raise
        finally:
            self.close()

    def executescript(self, script):
        """执行 SQL 脚本"""
        self.connect()
        try:
            cur = self.connection.cursor()
            cur.executescript(script)
            self.connection.commit()
            # print(f"执行sql语句成功:{script}")
            cur.close()
        except Exception as e:
            print(f"执行sql脚本失败:{script}!异常信息:{e.args[0]}")
            raise
        finally:
            self.close()

    @staticmethod
    def _dict_factory(cursor, row):
        d = {}
        for index, col in enumerate(cursor.description):
            d[col[0]] = row[index]
        return d

    def execute_dict(self, sql, values=()):
        self.connect()
        row = {}
        try:
            self.connection.row_factory = Sqlite._dict_factory
            cur = self.connection.cursor()
            cur.execute(sql, values)
            row = cur.fetchall()
            # print(f"执行sql语句成功:{sql}")
            cur.close()
        except Exception as e:
            print(f"执行sql语句失败:{sql}!异常信息:{e.args[0]}")
            raise
        # return row
        finally:
            self.connection.row_factory = self.row_factory   # 还原返回值数据结构
            self.close()
            return row

    def close(self):
        if self.connection:
            self.connection.close()
            self.connection = None
            # print(f"关闭Sqlite数据库:{self.db}成功!")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值