• python之内置sqlite3


    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    # @Author  : Yunhgu
    # @Software: Vscode
    # @Time    : 2021-04-20 08:17:24
    
    # 导入python3内置数据库驱动模块
    import sqlite3
    import os
    from logTool import logTool
    logger = logTool()
    
    
    class optionSqlite():
    
        def __init__(self, dbname="default.db"):
            # 连接到数据库,如果不存在就创建
            self.conn = sqlite3.connect(os.path.join(
                os.path.dirname(__file__), dbname))
            # 创建游标
            self.cur = self.conn.cursor()
            # 如果不存在便创建表
            self.cur.execute('''
            CREATE TABLE if not exists exchanges  (
            exchange_name varchar(50)  NOT NULL PRIMARY KEY,
            exchange_type varchar(15)  NOT NULL,
            bind_queue varchar(50),
            create_time datetime(6) NOT NULL,
            comment varchar(50)
            );
            ''')
            self.cur.execute('''CREATE TABLE if not exists queues  (
            virtual_host varchar(50)  NOT NULL PRIMARY KEY,
            queue_name varchar(50)  NOT NULL,
            create_time datetime(6) NOT NULL,
            comment varchar(50)
            );
            ''')
    
        # 将 db.row_factory 方法重写为 dict_factory 方法
        def dict_factory(self, cursor, row):
            d = {}
            for index, col in enumerate(cursor.description):
                d[col[0]] = row[index]
            return d
    
        # 插入数据
        def insert(self, sql):
            try:
                self.cur.execute(sql)  # 执行sql
                self.conn.commit()  # 增删改操作完数据库后,需要执行提交操作
                return True
            except Exception as e:
                logger.error("sqlite3 insert error and had rollback:%s", e)
                # 发生错误时回滚
                self.conn.rollback()
                return False
    
        # 查询数据
        def search(self, sql):
            try:
                # 调用重写的字典工厂方法,格式化查询的结果
                self.conn.row_factory = self.dict_factory
                cur = self.conn.cursor()
                queryResult = cur.execute(sql).fetchall()
                return queryResult
            except Exception as e:
                logger.error("sqlite3 insert error and had rollback:%s", e)
                return None
    
        # 更新数据
        def update(self, sql):
            try:
                self.cur.execute(sql)  # 执行sql
                self.conn.commit()  # 增删改操作完数据库后,需要执行提交操作
                return True
            except Exception as e:
                logger.error("sqlite3 update error and had rollback:%s", e)
                # 发生错误时回滚
                self.conn.rollback()
                return False
    
        # 删除数据
        def delete(self, sql):
            try:
                self.cur.execute(sql)  # 执行sql
                self.conn.commit()  # 增删改操作完数据库后,需要执行提交操作
                return True
            except Exception as e:
                logger.error("sqlite3 delete error and had rollback:%s", e)
                # 发生错误时回滚
                self.conn.rollback()
                return False
        
        # 关闭数据库链接
        def close(self):
            self.cur.commit()
            self.conn.close()
    
    
    if __name__ == '__main__':
        ops = optionSqlite()
        ops.insert(
            "INSERT INTO exchanges(exchange_name,exchange_type,create_time) VALUES('efg','direct',datetime('now', 'localtime'));")
        result = ops.search(
            "select exchanges.exchange_name,exchanges.exchange_type,exchanges.create_time from exchanges;")
        print(result)
    不论你在什么时候开始,重要的是开始之后就不要停止。 不论你在什么时候结束,重要的是结束之后就不要悔恨。
  • 相关阅读:
    loj#2540. 「PKUWC2018」随机算法
    loj#2538. 「PKUWC2018」Slay the Spire
    loj#2537. 「PKUWC2018」Minimax
    CF662C Binary Table
    bzoj4589: Hard Nim
    【HDU5909】Tree Cutting(FWT)
    P3175 [HAOI2015]按位或
    P4389 付公主的背包
    P4233 射命丸文的笔记
    GFS分布式文件系统环境部署与管理
  • 原文地址:https://www.cnblogs.com/yunhgu/p/14680114.html
Copyright © 2020-2023  润新知