Python3 簡單封裝 sqlite3 - SimpleToolSql


#coding: utf-8
#Author:boxker
#Mail:icjb@foxmail.com

import sqlite3
import os

class simpleToolSql():
    """
    simpleToolSql for sqlite3
    簡單數據庫工具類
    編寫這個類主要是為了封裝sqlite,繼承此類復用方法
    """

    def __init__(self,filename="stsql"):
        """
        初始化數據庫,默認文件名 stsql.db
        filename:文件名
        """
        self.filename = filename + ".db"
        self.db = sqlite3.connect(self.filename)
        self.c = self.db.cursor()
        
    def close(self):
        """
        關閉數據庫
        """
        self.c.close()
        self.db.close()

    def execute(self,sql,param=None):
        """
        執行數據庫的增、刪、改
        sql:sql語句
        param:數據,可以是list或tuple,亦可是None
        retutn:成功返回True
        """
        try:
            if param is None:
                self.c.execute(sql)
            else:
                if type(param) is list:
                    self.c.executemany(sql,param)
                else :
                    self.c.execute(sql,param)
            count = self.db.total_changes
            self.db.commit()
        except Exception as e:
            print(e)
            return False,e
        if count > 0 :
            return True
        else :
            return False

    def query(self,sql,param=None):
        """
        查詢語句
        sql:sql語句
        param:參數,可為None
        retutn:成功返回True
        """
        if param is None:
            self.c.execute(sql)
        else:
            self.c.execute(sql,param)
        return self.c.fetchall()
        
    # def set(self,table,field=" * ",where="",isWhere=False):
    #     self.table = table
    #     self.filed = field
    #     if where != "" :
    #         self.where = where
    #         self.isWhere = True
    #     return True

if __name__ == "__main__":
    """
    測試代碼
    """
    sql = simpleToolSql("test")
    f = sql.execute("create table test (id int not null,name text not null,age int);")
    print("ok")
    sql.execute("insert into test (id,name,age) values (?,?,?);",[(1,'abc',15),(2,'bca',16)])
    res = sql.query("select * from test;")
    print(res)
    sql.execute("insert into test (id,name) values (?,?);",(3,'bac'))
    res = sql.query("select * from test where id=?;",(3,))
    print(res)
    sql.close()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM