首页 > 数据库 >Python SQLite3 基本操作类

Python SQLite3 基本操作类

时间:2022-10-03 16:47:04浏览次数:52  
标签:return Python self sql ._ table SQLite3 基本操作 def

#!/usr/bin/env python  
# encoding: utf-8  
""" 
@version: v1.0 
@author: W_H_J 
@license: Apache Licence  
@contact: [email protected] 
@software: PyCharm 
@file: SQLite3Config.py 
@time: 2019/5/17 14:22 
@describe: sqllit3 操作助手
"""
import sys
import os
import sqlite3
 
sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
sys.path.append("..")
 
 
class ConnectSqlite:
 
    def __init__(self, dbName="./sqlite3Test.db"):
        """
        初始化连接--使用完记得关闭连接
        :param dbName: 连接库名字,注意,以'.db'结尾
        """
        self._conn = sqlite3.connect(dbName)
        self._cur = self._conn.cursor()
        self._time_now = "[" + sqlite3.datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S') + "]"
 
    def close_con(self):
        """
        关闭连接对象--主动调用
        :return:
        """
        self._cur.close()
        self._conn.close()
 
    def create_tabel(self, sql):
        """
        创建表初始化
        :param sql: 建表语句
        :return: True is ok
        """
        try:
            self._cur.execute(sql)
            self._conn.commit()
            return True
        except Exception as e:
            print(self._time_now, "[CREATE TABLE ERROR]", e)
            return False
 
    def drop_table(self, table_name):
        """
        删除表
        :param table_name: 表名
        :return:
        """
        try:
            self._cur.execute('DROP TABLE {0}'.format(table_name))
            self._conn.commit()
            return True
        except Exception as e:
            print(self._time_now, "[DROP TABLE ERROR]", e)
            return False
 
    def delete_table(self, sql):
        """
        删除表记录
        :param sql:
        :return: True or False
        """
        try:
            if 'DELETE' in sql.upper():
                self._cur.execute(sql)
                self._conn.commit()
                return True
            else:
                print(self._time_now, "[EXECUTE SQL IS NOT DELETE]")
                return False
        except Exception as e:
            print(self._time_now, "[DELETE TABLE ERROR]", e)
            return False
 
    def fetchall_table(self, sql, limit_flag=True):
        """
        查询所有数据
        :param sql:
        :param limit_flag: 查询条数选择,False 查询一条,True 全部查询
        :return:
        """
        try:
            self._cur.execute(sql)
            war_msg = self._time_now + ' The [{}] is empty or equal None!'.format(sql)
            if limit_flag is True:
                r = self._cur.fetchall()
                return r if len(r) > 0 else war_msg
            elif limit_flag is False:
                r = self._cur.fetchone()
                return r if len(r) > 0 else war_msg
        except Exception as e:
            print(self._time_now, "[SELECT TABLE ERROR]", e)
 
    def insert_update_table(self, sql):
        """
        插入/更新表记录
        :param sql:
        :return:
        """
        try:
            self._cur.execute(sql)
            self._conn.commit()
            return True
        except Exception as e:
            print(self._time_now, "[INSERT/UPDATE TABLE ERROR]", e)
            return False
 
    def insert_table_many(self, sql, value):
        """
        插入多条记录
        :param sql:
        :param value: list:[(),()]
        :return:
        """
        try:
            self._cur.executemany(sql, value)
            self._conn.commit()
            return True
        except Exception as e:
            print(self._time_now, "[INSERT MANY TABLE ERROR]", e)
            return False
 
 
class conTest:
    """测试类"""
 
    def __init__(self):
        self.con = ConnectSqlite("./sqlite3Test.db")
 
    def create_table_test(self):
        sql = '''CREATE TABLE `mytest` (
                  `id` DATETIME DEFAULT NULL,
                  `user` VARCHAR(12) DEFAULT NULL,
                  `name` VARCHAR(12) DEFAULT NULL,
                  `number` VARCHAR(12) DEFAULT NULL
                )'''
        print(self.con.create_tabel(sql))
 
    def drop_table_test(self):
        print(self.con.drop_table("mytest"))
 
    def fetchall_table_test(self):
        sql = "SELECT * from mytest WHERE user='1003';"
        sql_all = "SELECT * from mytest;"
        print("全部记录", self.con.fetchall_table(sql_all))
        print("单条记录", self.con.fetchall_table(sql_all, False))
        print("条件查询", self.con.fetchall_table(sql))
 
    def delete_table_test(self):
        sql = "DELETE FROM mytest WHERE user='1003';"
        print(self.con.delete_table(sql))
 
    def update_table_test(self):
        sql_update = "UPDATE mytest SET id={0},user={1},name={2},number={3} WHERE number={4}".format(1, 1002, "'王五'",
                                                                                                     1002,
                                                                                                     1002)
        print(self.con.insert_update_table(sql_update))
 
    def insert_table_test_one(self):
        sql = """INSERT INTO mytest VALUES (3, 1003, "王五", 1003);"""
        print(self.con.insert_update_table(sql))
 
    def insert_table_test_many(self):
        sql = """INSERT INTO mytest VALUES (?, ?, ?, ?)"""
        value = [(2, 1004, "赵六", 1004), (4, 1005, "吴七", 1005)]
        print(self.con.insert_table_many(sql, value))
 
    def close_con(self):
        self.con.close_con()
 
 
if __name__ == '__main__':
    contest = conTest()
    contest.create_table_test()
    contest.insert_table_test_many()
    contest.fetchall_table_test()
    contest.insert_table_test_one()
    contest.fetchall_table_test()
    contest.update_table_test()
    contest.drop_table_test()
    contest.close_con()

 

标签:return,Python,self,sql,._,table,SQLite3,基本操作,def
From: https://www.cnblogs.com/simadi/p/16750708.html

相关文章

  • python类型注解
    python类型注解functionannotation写法:使用冒号:加类型代表参数类型默认值参数示例:b:int=2使用->加类型代表返回值类型python解释器运行时并不会检查类型......
  • 使用Python实现读取TXT小说文件按每一回显示打印出来
    大家好,我是皮皮。一、前言前几天在Python铂金交流群【红色基因代代传】问了一个Python处理的问题,提问截图如下:文件里边的部分截图如下:大概的需求如下所示:二、实现过程这里【......
  • 盘点一个Python抓取有道翻译爬虫中的报错问题
    大家好,我是皮皮。一、前言前几天在Python白银交流群【斌】问了一个Python网络爬虫的问题,提问截图如下:报错截图如下:粉丝需要的数据如下:二、实现过程有道翻译之前有做过很多,确......
  • 将你的 Python 脚本转换为命令行程序
    使用Python中的​​scaffold​​​和​​click​​库,你可以将一个简单的实用程序升级为一个成熟的命令行界面工具。在我的职业生涯中,我写过、用过和看到过很多随意的......
  • 常见工程、应用、学习错误及安装问题之Python
    ​​pip临时使用国内镜像源​​​​python创建文件夹​​​​python读取文件下所有文件路径​​​​将numpy中的True/False转换成1/0​​​​使用python复制文件​​​​L......
  • 为python安装扩展模块时报错——error: invalid command 'bdist_wheel'
    具体过程: devil@hp:~/lab$./bazel-bin/python/pip_package/build_pip_package/tmp/dmlab_pkg2022年10月03日星期一14:05:54CST:===Buildingwheelusage:setu......
  • python pygame 迷宫生成
    importrandomimportsysimportpygame#使用pygame之前必须初始化pygame.init()#参数设置box_w,box_h=5,5#盒子宽高window_w,window_h=400,400x,y=0,0#盒......
  • python pygame 生命的游戏
    importsysimportpygameimportrandom#参数设置box_w,box_h=10,10#盒子宽高window_w,window_h=400,400x,y=0,0#使用pygame之前必须初始化pygame.init()#设......
  • 学习python遇到的问题
    python重定向输入:io.UnsupportedOperation:notreadable两处错误一、用open打开一个文件,此时调用的是w写入模式,下面使用read是没有权限的,得使用w+读写模式二、使用wri......
  • python学习:multiprocessing多进程-Pool进程池模块
    Multiprocessing.Pool可以提供指定数量的进程供用户调用,当有新的请求提交到pool中时,如果池还没有满,那么就会创建一个新的进程用来执行该请求;但如果池中的进程数已经达到规定......