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)
    # []
相关推荐
宇卿.6 分钟前
Java键盘输入语句
java·开发语言
Amo Xiang16 分钟前
2024 Python3.10 系统入门+进阶(十五):文件及目录操作
开发语言·python
liangbm326 分钟前
数学建模笔记——动态规划
笔记·python·算法·数学建模·动态规划·背包问题·优化问题
friklogff29 分钟前
【C#生态园】提升C#开发效率:深入了解自然语言处理库与工具
开发语言·c#·区块链
B站计算机毕业设计超人37 分钟前
计算机毕业设计Python+Flask微博情感分析 微博舆情预测 微博爬虫 微博大数据 舆情分析系统 大数据毕业设计 NLP文本分类 机器学习 深度学习 AI
爬虫·python·深度学习·算法·机器学习·自然语言处理·数据可视化
羊小猪~~41 分钟前
深度学习基础案例5--VGG16人脸识别(体验学习的痛苦与乐趣)
人工智能·python·深度学习·学习·算法·机器学习·cnn
重生之我在20年代敲代码2 小时前
strncpy函数的使用和模拟实现
c语言·开发语言·c++·经验分享·笔记
爱上语文2 小时前
Springboot的三层架构
java·开发语言·spring boot·后端·spring
waterHBO3 小时前
python 爬虫 selenium 笔记
爬虫·python·selenium
编程零零七4 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql