Python操作Sqlite的简单封装

文章目录


一、安装依赖

bash 复制代码
pip install numpy

二、配置文件

utils.config.py

python 复制代码
############### 233 SQLITE Configuration ###############
SQLITE_PATH = './mysqlite.db'

三、实现类

utils.PostGreOp.py

python 复制代码
# encoding: utf-8

import json
import sqlite3
import numpy as np
from utils import config as cf



class SqliteOp(object):

    def __init__(self, db_path=cf.SQLITE_PATH):
        print(f"db_path: {db_path}")
        self.db_path = db_path
        # conn = sqlite3.connect('./test.db')

    # 增删改
    def operate(self, sql):
        db = sqlite3.connect(self.db_path)
        cur = db.cursor()
        try:
            # 执行sql语句
            cur.execute(sql)
            op_id = cur.lastrowid
            cur.close()
            # 提交到数据库执行
            db.commit()
        except Exception as e:
            print(e)

            op_id = None

            cur.close()
            # Rollback in case there is any error
            db.rollback()
        # 关闭数据库连接
        db.close()

        return op_id


    # 查
    def select(self, sql):
        db = sqlite3.connect(self.db_path)
        cur = db.cursor()
        results = None
        try:
            # 执行sql语句
            cur.execute(sql)
            # 获取所有记录列表
            results = cur.fetchall()
            # print(results)
        except Exception as e:
            print(e)
            # 关闭数据库连接
        db.close()
        return results

    @classmethod
    def escape_str(cls, text):
        '''
        string类型数据导入时有可能出现单双引号等需要转义的字段,也可能出现nan这样的字段,需要先处理一下
        :return:
        '''
        if cls.isNaNo(text):
            return 'null'
        else:
            return "'" + json.dumps(str(text), ensure_ascii=False)[1:-1] + "'"

    @classmethod
    def escape_num(cls, text):
        '''
        转一下整数,报错的话说明传入的不是数字,有sql注入风险
        :return:
        '''
        if str(text) == '0':
            return '0'
        elif cls.isNaNo(text):
            return 'null'
        else:
            # return json.dumps(str(text), ensure_ascii=False)
            try:
                int(text)
                return str(text)
            except Exception as e:
                raise Exception('传入不是数字,有sql注入风险')


        # if cls.isNaNo(text):
        #     return 'null'
        # else:
        #     return json.dumps(str(text), ensure_ascii=False)

    @classmethod
    def isNaNo(cls, sth):
        '''
        NaN、None或者空字符串返回True,其他情况返回False
        '''
        if not sth:
            return True
        if isinstance(sth, float):
            if np.isnan(sth):
                return True
        return False



if __name__ == '__main__':

    # 指定目录下没有数据库的话会自动创建
    sqlt = SqliteOp(db_path='./mysqlite.db')

    # 查询当前数据库下的所有表
    res = sqlt.select(f'''SELECT name FROM sqlite_master WHERE type='table';''')
    print(res)
    # []
相关推荐
从0至1几秒前
C++编程入门:从基础到复合类型
开发语言·c++
java1234_小锋2 分钟前
【NLP舆情分析】基于python微博舆情分析可视化系统(flask+pandas+echarts) 视频教程 - 热词数量分析日期统计功能实现
python·自然语言处理·flask
山烛17 分钟前
KNN 算法中的各种距离:从原理到应用
人工智能·python·算法·机器学习·knn·k近邻算法·距离公式
guozhetao30 分钟前
【ST表、倍增】P7167 [eJOI 2020] Fountain (Day1)
java·c++·python·算法·leetcode·深度优先·图论
墨染点香36 分钟前
第七章 Pytorch构建模型详解【构建CIFAR10模型结构】
人工智能·pytorch·python
枫叶丹41 小时前
【Qt开发】信号与槽(二)-> 信号和槽的使用
开发语言·qt
阿什么名字不会重复呢1 小时前
在线工具+网页平台来学习和操作Python与Excel相关技能
python·数据分析
大熊程序猿1 小时前
net8.0一键创建支持(Orm-Sqlite-MySql-SqlServer)
数据库·mysql·sqlite
Vertira2 小时前
python 阿里云 安装 dashscope的简介、安装
开发语言·python
gc_22992 小时前
学习Python中Selenium模块的基本用法(1:简介)
python·selenium