Python SQLite3 基本操作類

簡介

SQLite3只是一個輕型的嵌入式數據庫引擎,佔用資源非常低,處理速度比Mysql還快,專門用於移動設備上進行適量的數據存取,它只是一個文件,不需要服務器進程。

SQLite是一個進程內的庫,實現了自給自足的、無服務器的、零配置的、事務性的 SQL 數據庫引擎。它是一個零配置的數據庫,這意味着與其他數據庫一樣,您不需要在系統中配置。

就像其他數據庫,SQLite 引擎不是一個獨立的進程,可以按應用程序需求進行靜態或動態連接。SQLite 直接訪問其存儲文件。

爲什麼要用 SQLite?

  • 不需要一個單獨的服務器進程或操作的系統(無服務器的)。

  • SQLite 不需要配置,這意味着不需要安裝或管理。

  • 一個完整的 SQLite 數據庫是存儲在一個單一的跨平臺的磁盤文件。

  • SQLite 是非常小的,是輕量級的,完全配置時小於 400KiB,省略可選功能配置時小於250KiB。

  • SQLite 是自給自足的,這意味着不需要任何外部的依賴。

  • SQLite 事務是完全兼容 ACID 的,允許從多個進程或線程安全訪問。

  • SQLite 支持 SQL92(SQL2)標準的大多數查詢語言的功能。

  • SQLite 使用 ANSI-C 編寫的,並提供了簡單和易於使用的 API。

  • SQLite 可在 UNIX(Linux, Mac OS-X, Android, iOS)和 Windows(Win32, WinCE, WinRT)中運行。

SQLite Python操作類 

#!/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()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章