sqlite封裝

import sqlite3


class MySqLite():
    def __init__(self, db_name=None):
        if db_name:
            db_name = db_name + ".db"
        else:
            db_name = ":memory:"
        self.db_name = db_name

    def start_conn(self):
        self.conn = sqlite3.connect(self.db_name)

    def close(self):
        self.conn.close()

    def creat_table(self, table_name="", fields="", sql="", index=""):
        """
        fileds,index 均為以逗號(hào)連接的字段形成的字符串
        """
        self.start_conn()
        cursor = self.conn.cursor()

        if not sql:
            sql = f"""
            CREATE TABLE `{table_name}`
                (
                id integer   PRIMARY KEY AUTOINCREMENT,
                insert_time timestamp NULL default CURRENT_TIMESTAMP,
                {" varchar(1000), ".join(fields.split(",")) + " varchar(1000)"}     
                 );
            """
        cursor.execute(sql)
        if index:
            for col_name in index.split(","):
                cursor.execute(f"""CREATE INDEX {col_name} ON `{table_name}` ({col_name})""")

        self.conn.commit()
        self.conn.close()

    def insert(self, table_name, data):
        """
        data 可以是字典插入一行,也可以是列表插入多行
        data = {"name":"aaa","age":18}
        data = [{"name":"aaa","age":18},{"name":"bb","age":19}]

        """
        self.start_conn()
        cursor = self.conn.cursor()
        if isinstance(data, dict):
            fields = ",".join(data.keys())
            values = "(\"" + "\",\"".join([str(data.get(k)) for k in data.keys()]) + "\")"

        if isinstance(data, list):
            fields = ",".join(data[0].keys())
            values = ",".join(["(\"" + "\",\"".join([str(dic.get(k)) for k in data[0].keys()]) + "\")" for dic in data])

        cursor.execute(f"INSERT INTO `{table_name}` ({fields}) VALUES {values}")
        self.conn.commit()
        self.conn.close()

    def query(self, table_name, files="", where=""):
        """
        只返回前100條
        有files則返回json格式,無(wú)files全部查詢(xún)返回列表形式
        """
        self.start_conn()
        cursor = self.conn.cursor()
        files = "*" if not files else files
        sql = f"SELECT {files} from `{table_name}`"
        if where:
            sql += "where " + where
        res = []
        for i in cursor.execute(sql):
            if len(res) > 100:
                break
            res.append(i)
        if files != "*":
            res = [dict(zip(files.split(","), i)) for i in res]
        self.conn.close()
        return res

    def execute(self, sql):
        """
         sql 語(yǔ)句
        "SELECT id, name, address, salary  from COMPANY"
        "UPDATE COMPANY set SALARY = 25000.00 where ID=1"
        "DELETE from COMPANY where ID=2;"

        """
        self.start_conn()
        cursor = self.conn.cursor()
        cursor.execute(sql)
        self.conn.commit()
        self.conn.close()


if __name__ == '__main__':
    slite = MySqLite("test")
    slite.creat_table(table_name="user", fields="name,age,class,job", index="name,class")

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容